当前位置:网站首页>Asynchronous, email and scheduled tasks
Asynchronous, email and scheduled tasks
2022-07-03 01:05:00 【Running Wang Mumu sir】
Mission
Asynchronous task
establish
servicepackage , Create a class under itAsyncServiceForgery is processing data , Cause thread delay , Analog synchronization waiting .
package com.hxl.service; import org.springframework.stereotype.Service; @Service public class AsyncService { public void hello(){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(" Data processing ...."); } }establish
controllerpackage , Create a class under itAsyncControllerpackage com.hxl.controller; import com.hxl.service.AsyncService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class AsyncController { @Autowired AsyncService asyncService; @RequestMapping("/hello") public String hello(){ asyncService.hello(); return " No problem "; } }Access test
http://localhost:8080/hello, At this time, you can find the web page waiting 3 It will appear in secondsNo problemThe words... . This is the situation of synchronous waiting .In order to make the user experience better , Let the user get the message first , Then the background uses multithreading to process the results . We need to add a comment , such ,Springboot Will open a thread pool , To call .
// tell Spring This is an asynchronous method @Async public void hello(){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(" Data processing ...."); }You also need to add an annotation to the main launcher , Let the asynchronous annotation turn on
@EnableAsync // Turn on the asynchronous annotation function @SpringBootApplication public class SpringbootAsyncApplication { public static void main(String[] args) { SpringApplication.run(SpringbootAsyncApplication.class, args); } }At this time, the test found , The web page will open instantly , But the background data will continue , Until the end of data processing .
Email tasks
Introduce dependencies
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>You can see the relevant email sending dependencies

see
JavaMailSenderImplAfter finding it , Look at the configuration file, that ispropertiesUnder the , We can see the relevant configurationtake QQ The service in the mailbox is turned on , We use IMAP/SMTP service

The configuration file
[email protected] spring.mail.password= Their own QQ Authorization code spring.mail.host=smtp.qq.com spring.mail.properties.mail.smtp.ssl.enable=truetest
package com.hxl; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; @SpringBootTest class SpringbootAsyncApplicationTests { @Autowired JavaMailSenderImpl mailSender; @Test void contextLoads() { // A simple email SimpleMailMessage message = new SimpleMailMessage(); message.setSubject(" Tomorrow will be a holiday "); message.setText(" direct 10 Day long vacation "); message.setTo("[email protected]"); message.setFrom("[email protected]"); mailSender.send(message); } @Test public void contextLoads2() throws MessagingException { // A complicated email MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setSubject(" Tomorrow will be a holiday "); helper.setText("<b style='color:red'> What do you think </b>",true); // Sending attachments helper.addAttachment("1.jpg",new File(" Path to file ")); helper.addAttachment("2.jpg",new File(" such as :D:\\2.jpg")); helper.setTo("[email protected]"); helper.setFrom("[email protected]"); mailSender.send(mimeMessage); } }Then you can see that our email was sent successfully .
Timing task
TaskExecutor Interface
TaskScheduler Interface
Two notes :
- @EnableScheduling // Note on timing function , In the main boot class
- @Scheduled // When to execute
test
establish
Servicepackage , Create a classScheduledServicepackage com.hxl.service; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; @Service public class ScheduledService { // Execute this method at a specific time //cron expression // second branch when Japan month What day of the week // The following sentence is from Monday to Sunday , Of 0 second @Scheduled(cron = "0 * * * * 0-7") public void hello(){ System.out.println("hello, You've been executed "); } }Add... To the main program @EnableScheduling Turn on timed task function
package com.hxl; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; @EnableAsync // Turn on the asynchronous annotation function @EnableScheduling // Note on timing function @SpringBootApplication public class SpringbootAsyncApplication { public static void main(String[] args) { SpringApplication.run(SpringbootAsyncApplication.class, args); } }And then it's all right
cron expression
cron:https://baike.baidu.com/item/cron/10952601?fr=aladdin
cron Generation :https://www.bejson.com/othertools/cron/
边栏推荐
- 【爱死机】《吉巴罗》被忽略的细节
- Leetcode-934: the shortest Bridge
- tail -f 、tail -F、tailf的区别
- RK3568开发板评测篇(二):开发环境搭建
- 寻找标杆战友 | 百万级实时数据平台,终身免费使用
- Tensorflow 2. Chapter 15 of X (keras) source code explanation: migration learning and fine tuning
- MongoDB系列之MongoDB常用命令
- leetcode-1964:找出到每个位置为止最长的有效障碍赛跑路线
- leetcode-849:到最近的人的最大距离
- Is there a free text to speech tool to help recommend?
猜你喜欢

【AutoSAR 二 AppL概述】

拥抱平台化交付的安全理念

tail -f 、tail -F、tailf的区别
![[C language] branch and loop statements (Part 1)](/img/47/6efcc59bd26e26f66c698635c26c8b.png)
[C language] branch and loop statements (Part 1)

Matlab saves the digital matrix as geospatial data, and the display subscript index must be of positive integer type or logical type. Solve the problem

电话网络问题

这不平凡的两年,感谢我们一直在一起!

合并K个已排序的链表

有向图的强连通分量

(C language) data storage
随机推荐
Leetcode-1964: find the longest effective obstacle race route to each position
The arm core board / development board of Feiling equipped with Ti am62x made its debut in embedded world 2022
Hdu3507 (slope DP entry)
鏈錶內指定區間反轉
[shutter] image component (configure local GIF image resources | load placeholder with local resources)
[overview of AUTOSAR four BSW]
Reading and writing speed of Reza rz/g2l arm development board storage and network measurement
关于Fibonacci数列
Leetcode-2280: represents the minimum number of line segments of a line graph
递归处理组织的几种情况
Data analysis, thinking, law breaking and professional knowledge -- analysis method (I)
Delete duplicate elements in the ordered linked list -ii
【AutoSAR 一 概述】
Thank you for being together for these extraordinary two years!
Inversion de l'intervalle spécifié dans la liste des liens
matlab 多普勒效应产生振动信号和处理
【AutoSAR 八 OS】
1038 Recover the Smallest Number
[overview of AUTOSAR three RTE]
全志A40i/T3如何通过SPI转CAN