当前位置:网站首页>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/
边栏推荐
- 【AutoSAR 十三 NVM】
- 2022 list of manufacturers of Chinese 3D vision enterprises (guided positioning and sorting scenes)
- Basic use of sringcloud & use of component Nacos
- mysql 多表联合删除
- Assets, vulnerabilities, threats and events of the four elements of safe operation
- RISA rz/g2l processor introduction | frame diagram | power consumption | schematic diagram and hardware design guide
- cordova-plugin-device获取设备信息插件导致华为审核不通过
- [overview of AUTOSAR four BSW]
- 瑞萨RZ/G2L ARM开发板存储读写速度与网络实测
- 【AutoSAR 九 C/S原理架构】
猜你喜欢

(C language) data storage

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

【爱死机】《吉巴罗》被忽略的细节

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

有向图的强连通分量

数据分析思维分析犯法和业务知识——分析方法(一)

基于ARM RK3568的红外热成像体温检测系统
![[shutter] image component (configure local GIF image resources | load placeholder with local resources)](/img/73/19e2e0fc5ea6f05e34584ba40a452d.jpg)
[shutter] image component (configure local GIF image resources | load placeholder with local resources)

Advanced pointer (I)

飞凌搭载TI AM62x的ARM核心板/开发板首发上市,亮相Embedded World 2022
随机推荐
1.12 - Instructions
ROS2之ESP32简单速度消息测试(极限频率)
Arduino开发之按键检测与正弦信号输出
Is there a free text to speech tool to help recommend?
Vulkan is not a "panacea"“
lex && yacc && bison && flex 配置的问题
Leetcode-1964: find the longest effective obstacle race route to each position
How to convert Quanzhi a40i/t3 to can through SPI
Meaning of Tencent cloud free SSL certificate extension file
百度智能云牵头打造智能云综合标准化平台
递归处理组织的几种情况
研发一款国产ARM智能边缘计算网关需要什么
1038 Recover the Smallest Number
无向图的割点
Cordova plugin device obtains the device information plug-in, which causes Huawei to fail the audit
Win10 多种方式解决无法安装.Net3.5的问题
(C language) data storage
【AutoSAR 二 AppL概述】
Merge K sorted linked lists
Vulkan performance and refinement