Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize SpringBoot Asynchronous, Mail Task and scheduled Task

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "SpringBoot asynchronism, mail tasks, timing tasks how to achieve". In daily operation, I believe many people have doubts about how to achieve SpringBoot asynchronism, mail tasks and timing tasks. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "SpringBoot asynchronism, mail tasks, timing tasks". Next, please follow the editor to study!

Asynchronous task

1. Create a service package

2. Create a class AsyncService

Asynchronous processing is still very common. For example, when we send an email on a website, the backend will send the email, and the foreground will cause the response to remain motionless, and the response will not be successful until the email is sent. Therefore, we usually use a multi-threaded approach to deal with these tasks.

Write a method that pretends to be processing data and uses threads to set some delays to simulate synchronous waiting

@ Servicepublic class AsyncService {public void hello () {try {Thread.sleep (3000);} catch (InterruptedException e) {e.printStackTrace ();} System.out.println ("business in progress");}}

3. Write controller package

4. Write the AsyncController class

Let's write a Controller test.

@ RestControllerpublic class AsyncController {@ Autowired AsyncService asyncService; @ GetMapping ("/ hello") public String hello () {asyncService.hello (); return "success";}}

5. Visit http://localhost:8080/hello for testing, and success appears 3 seconds later, which is the case of synchronous waiting.

Question: if we want users to get the message directly, we can use multithreading in the background, but each time we need to write the implementation of multithreading manually, which is too troublesome. We just need to use a simple method and add a simple note to our method, as follows:

6. Add @ Async annotation to the hello method

/ / tell Spring that this is an asynchronous method @ Asyncpublic void hello () {try {Thread.sleep (3000);} catch (InterruptedException e) {e.printStackTrace ();} System.out.println ("business in progress");}

SpringBoot will open its own thread pool and make calls! But for this annotation to take effect, we also need to add an annotation @ EnableAsync to the main program to enable the asynchronous annotation function.

@ EnableAsync / / enable the asynchronous annotation function @ SpringBootApplicationpublic class SpringbootTaskApplication {public static void main (String [] args) {SpringApplication.run (SpringbootTaskApplication.class, args);}}

7. Restart the test, the web page responds instantly, and the background code is still executed!

Mail task

Sending mail is also very common in our daily development, and Springboot also helps us to do support.

Spring-boot-start-mail needs to be introduced to send mail.

SpringBoot automatically configures MailSenderAutoConfiguration

Define MailProperties content and configure it in application.yml

Automatic assembly JavaMailSender

Test email delivery

Test:

1. Introduce pom dependency

Org.springframework.boot spring-boot-starter-mail

If you look at the dependencies it introduces, you can see that jakarta.mail

Com.sun.mail jakarta.mail 1.6.4 compile

2. View the automatic configuration class: MailSenderAutoConfiguration

Bean,JavaMailSenderImpl exists in this class

Then let's take a look at the configuration file.

@ ConfigurationProperties (prefix = "spring.mail") public class MailProperties {private static final Charset DEFAULT_CHARSET; private String host; private Integer port; private String username; private String password; private String protocol = "smtp"; private Charset defaultEncoding; private Map properties; private String jndiName;}

3. Configuration file application.yaml:

Spring: mail: username: 363421658@qq.com password: waeplteonlgcbhhf host: smtp.qq.com properties: mail: smtp: ssl: enable:true

Get the authorization code: set up in QQ Mail-> account-> Open pop3 and smtp services, and obtain the password replacement string needed when the three parties log in.

4. Spring unit test

Package com.credithc.kg;import org.junit.Test;import org.junit.runner.RunWith;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 org.springframework.test.context.junit4.SpringRunner;import javax.mail.MessagingException;import javax.mail.internet.MimeMessage;import java.io.File / * @ author sowhat * @ create 2020-08-27 12:32 * / @ RunWith (SpringRunner.class) @ SpringBootTestpublic class FeatureAppTest {@ Autowired JavaMailSenderImpl mailSender; @ Testpublic void contextLoads () {/ / email setting 1: a simple email SimpleMailMessage message = new SimpleMailMessage (); message.setSubject ("Notification-come to work overtime tomorrow") Message.setText ("meeting at 7:30 tonight"); message.setTo ("363421658@qq.com"); message.setFrom ("363421658@qq.com"); mailSender.send (message) } @ Test public void contextLoads2 () throws MessagingException {/ / email Settings 2: a complex email MimeMessage mimeMessage = mailSender.createMimeMessage (); / / multiple files MimeMessageHelper helper = new MimeMessageHelper (mimeMessage, true, "utf-8"); helper.setSubject ("Notification-overtime tomorrow") Helper.setText ("come to the meeting at 7:30 today", true); / / send attachment helper.addAttachment ("1.png", new File ("C:\ Users\\ DELL-3020\\ Desktop\ 1.png"); helper.setTo ("363421658@qq.com"); helper.setFrom ("363421658@qq.com") MailSender.send (mimeMessage);}}

Check the mailbox, the email has been received successfully!

We only need to use Thymeleaf for front and back end combination to develop our own website email sending and receiving function!

Scheduled task

Project development often needs to perform some scheduled tasks, such as the need to analyze the log information of the previous day in the early hours of every day. Spring provides us with a way to schedule tasks asynchronously and provides two interfaces.

TaskExecutor interface

TaskScheduler interface

Two notes:

@ EnableScheduling

@ Scheduled

Cron is the same as crontab in Linux:

Test steps:

1. Create a ScheduledService

There is a hello method in us, which needs to be executed regularly. How to deal with it?

/ / No action is required when enabled, and the system will automatically call @ Servicepublic class ScheduledService {/ / seconds, hours, days and months / / 0 * MON-FRI / / pay attention to the use of cron expressions when the time comes @ Scheduled (cron = "0 * 0-7") public void hello () {System.out.println ("hello.");}}

2. After writing scheduled tasks here, we need to add @ EnableScheduling to the main program to enable timed tasks.

@ EnableAsync / / enable asynchronous annotations @ EnableScheduling / / enable annotation-based scheduled tasks @ SpringBootApplicationpublic class SpringbootTaskApplication {public static void main (String [] args) {SpringApplication.run (SpringbootTaskApplication.class, args);}}

3. Let's take a closer look at cron expressions.

Field permissible integers for special character seconds (Seconds) 0x 59,-* / four character minutes (Minutes) 0x 59,-* / four character hours (Hours) 0mm 23,-* / four character dates (DayofMonth) 1x 31 (but you need to consider the number of days of your month),-*? / L W C eight character months (Month) 1x 12 or JAN-DEC -* / four character week (DayofWeek) 1 / 7 integer or SUN-SAT (1=SUN),-*? / L C # eight character years (optional Left blank) (Year) 1970-2099,-* / four characters

PS: several demo

(1) 0Universe 2 *? It means that the task is executed every 2 seconds (1) 00 ram 2 *? Indicates that the task is executed every 2 minutes (1) 0 0 21 *? To adjust the task at 2: 00 a.m. on the 1st of each month (2) 015 10? * MON-FRI means to perform homework at 10:15 every day from Monday to Friday. (3) 015 10? 6L 2002-2006 means that the last Friday of every month from 2002 to 2006 will be executed at 10:15 in the morning. 10:00, 2pm, 4pm every day (5) 00pm 30 9-17 *? From 9 am to 5 am, every half hour during working hours (6) 0012? * WED means 12:00 every Wednesday (7) 0012 *? Trigger (8) 0 15 10 every day at 12:00? * * trigger (9) 0 15 10 * * at 10:15 every morning? Trigger (10) 0 15 10 * * at 10:15 every morning? Trigger at 10:15 every day (11) 0 15 10 * *? 10:15 every day in 2005 trigger (12) 0 * 14 * *? Trigger every minute between 2pm and 2:59 every day (13) 00 Universe 5 14 * *? Trigger every 5 minutes between 2pm and 2:55 every day (14) 00 stroke 5 14re18 * *? Trigger (15) 00-5 14 * every 5 minutes between 2 p.m. and 2:55 and 6 p.m. and 6:55 every day. Trigger every minute from 2 p.m. to 2:05 every day (16) 0 10 WED 44 14? 3 WED trigger at 2:10 and 2:44 on Wednesdays in March every year (17) 0 15 10? * 10:15 from Monday to Friday * trigger (18) 0 15 10 15 *? Trigger at 10:15 on the 15th of each month (19) 0 15 10 L *? Trigger at 10:15 on the last day of each month (20) 015 10? * 6L trigger at 10:15 on the last Friday of each month (21) 0 15 10? * 6L 2002-2005 trigger at 10:15 on the last Friday of each month from 2002 to 2005 (22) 015 10? * 6L 3 trigger at 10:15 on the third Friday of each month On the "SpringBoot asynchronism, mail tasks, scheduled tasks how to achieve" the end of the study, I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 243

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report