当前位置:网站首页>Asynchronous, email and scheduled tasks
Asynchronous, email and scheduled tasks
2022-07-03 01:05:00 【Running Wang Mumu sir】
Mission
Asynchronous task
establish
service
package , Create a class under itAsyncService
Forgery 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
controller
package , Create a class under itAsyncController
package 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 problem
The 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
JavaMailSenderImpl
After finding it , Look at the configuration file, that isproperties
Under 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=true
test
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
Service
package , Create a classScheduledService
package 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/
边栏推荐
- Correctly distinguish the similarities and differences among API, rest API, restful API and web service
- leetcode:701. 二叉搜索树中的插入操作【bst的插入】
- 瑞萨电子RZ/G2L开发板上手评测
- [case sharing] let the development of education in the new era advance with "number"
- Hdu3507 (slope DP entry)
- Leetcode-2115: find all the dishes that can be made from the given raw materials
- leetcode-849:到最近的人的最大距离
- 详解RDD基本概念、RDD五大属性
- excel IF公式判断两列是否相同
- Understanding and distinguishing of some noun concepts in adjustment / filtering
猜你喜欢
Explain the basic concepts and five attributes of RDD in detail
安全运营四要素之资产、脆弱性、威胁和事件
Hdu3507 (slope DP entry)
寻找标杆战友 | 百万级实时数据平台,终身免费使用
2022 list of manufacturers of Chinese 3D vision enterprises (guided positioning and sorting scenes)
Unity learns from spaceshooter to record the difference between fixedupdate and update in unity for the second time
Rk3568 development board evaluation (II): development environment construction
[overview of AUTOSAR three RTE]
matlab 多普勒效应产生振动信号和处理
Embrace the safety concept of platform delivery
随机推荐
Delete duplicate elements in the ordered linked list -ii
In the first half of 2022, there are 10 worth seeing, and each sentence can bring you strength!
Win10 can't be installed in many ways Problems with NET3.5
飞凌搭载TI AM62x的ARM核心板/开发板首发上市,亮相Embedded World 2022
瑞萨电子RZ/G2L开发板上手评测
Merge K sorted linked lists
Problèmes de configuration lex & yacc & Bison & Flex
Solve the cache problem of reactnative using WebView
Leetcode-1964: find the longest effective obstacle race route to each position
1.12 - 指令
[AUTOSAR XIII NVM]
[AUTOSAR 11 communication related mechanism]
Leetcode-224: basic calculator
Kubernetes resource object introduction and common commands (V) - (NFS & PV & PVC)
lex && yacc && bison && flex 配置的问题
MongoDB系列之MongoDB常用命令
Vulkan is not a "panacea"“
瑞萨RZ/G2L 处理器简介|框架图|功耗|原理图及硬件设计指南
Thank you for being together for these extraordinary two years!
Is there a free text to speech tool to help recommend?