当前位置:网站首页>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/
边栏推荐
- [case sharing] let the development of education in the new era advance with "number"
- [AUTOSAR + IO Architecture]
- 2022 list of manufacturers of Chinese 3D vision enterprises (guided positioning and sorting scenes)
- 删除有序链表中重复的元素-II
- 【AutoSAR 三 RTE概述】
- Assets, vulnerabilities, threats and events of the four elements of safe operation
- 465. 最优账单平衡 DFS 回溯
- 【AutoSAR 十二 模式管理】
- Leetcode-934: the shortest Bridge
- How to find out the currently running version of Solr- How do I find out version of currently running Solr?
猜你喜欢
![[AUTOSAR II appl overview]](/img/da/76ccc05e2199705b20d8304bfb86b2.png)
[AUTOSAR II appl overview]

寻找标杆战友 | 百万级实时数据平台,终身免费使用

Explain the basic concepts and five attributes of RDD in detail

1.11 - 总线

Vulkan practice first bullet
![[AUTOSAR eight OS]](/img/ac/fbc84c077ff9c94c840e1871171d19.png)
[AUTOSAR eight OS]

RISA rz/g2l processor introduction | frame diagram | power consumption | schematic diagram and hardware design guide

世平信息首席科学家吕喆:构建以数据和人员为中心的安全能力

【AutoSAR 八 OS】

【AutoSAR 四 BSW概述】
随机推荐
拥抱平台化交付的安全理念
Reading and writing speed of Reza rz/g2l arm development board storage and network measurement
leetcode-871:最低加油次数
mysql 多表联合删除
lex && yacc && bison && flex 配置的问题
lex && yacc && bison && flex 配置的問題
Thread start and priority
【AutoSAR 九 C/S原理架构】
[AUTOSAR VI description document]
[AUTOSAR + IO Architecture]
Leetcode-1964: find the longest effective obstacle race route to each position
Correctly distinguish the similarities and differences among API, rest API, restful API and web service
【AutoSAR 八 OS】
How to systematically learn machine learning
KingbaseES ALTER TABLE 中 USING 子句的用法
[applet project development -- JD mall] user defined search component of uni app (middle) -- search suggestions
Leetcode-849: maximum distance to the nearest person
leetcode-2280:表示一个折线图的最少线段数
数学建模之线性规划(含MATLAB代码)
[AUTOSAR eight OS]