springboot(19)-asynchronous, timed, mail task

1 Asynchronous tasks

1. Create a service package
2. Create a class AsyncService

Asynchronous processing is still very commonly used. For example, when we send emails on the website, the background will send emails. At this time, the foreground will cause the response to be inactive. The response will not succeed until the email is sent, so we generally use multi-threaded methods. Deal with these tasks.
AsyncService.java

package com.zs.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("业务进行中....");
    }
}

Visit http://localhost:8080/hello for testing. Success appears after 3 seconds. This is a synchronous waiting situation.
Insert picture description here
If we want the user to get the message directly, we can use multi-threaded processing in the background, but every time If you need to manually write a multi-threaded implementation by yourself, it is too troublesome, we only need to use a simple method, add a simple annotation
to our method to add @Async annotation to the hello method

@Service
public class AsyncService {
    
    

    @Async //告诉Spring这是一个异步方法
    public void hello(){
    
    
        try {
    
    
            Thread.sleep(3000);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        System.out.println("业务进行中....");
    }
}

SpringBoot will open a thread pool by itself 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 //开启异步注解功能
@SpringBootApplication
public class SprintbootTaskApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(SprintbootTaskApplication.class, args);
    }
}

Restart the test, the webpage responds instantly, and the background code is still executed

2 Mail task

Email sending is also very much in our daily development. Springboot also helped us to support it.
Email sending needs to introduce spring-boot-start-mail
SpringBoot automatically configure MailSenderAutoConfiguration to
define MailProperties content, configure it in application.yml,
automatically assemble JavaMailSender
Test mail sending

Dependency injection

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

View MailSenderAutoConfiguration automatic configuration class
Insert picture description here
configuration property file

Insert picture description here
application.properties

spring.mail.username=930312043@qq.com
spring.mail.password=bpwekhqfkzehbfee
spring.mail.host=smtp.qq.com
# qq需要配置ssl
spring.mail.properties.mail.smtp.ssl.enable=true

The method of obtaining spring.mail.password
Insert picture description here
Spring unit test

package com.zs;

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;

@SpringBootTest
class SprintbootTaskApplicationTests {
    
    
    @Autowired
    JavaMailSenderImpl mailSender;
    @Test
    void contextLoads() {
    
    
        //邮件设置1:一个简单的邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("通知-明天来狂神这听课");
        message.setText("今晚7:30开会");

        message.setTo("[email protected]");
        message.setFrom("[email protected]");
        mailSender.send(message);
    }
}
@Test
public void contextLoads2() throws MessagingException {
    
    
   //邮件设置2:一个复杂的邮件
   MimeMessage mimeMessage = mailSender.createMimeMessage();
   MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

   helper.setSubject("通知-明天来狂神这听课");
   helper.setText("<b style='color:red'>今天 7:30来开会</b>",true);

   //发送附件
   helper.addAttachment("1.jpg",new File(""));
   helper.addAttachment("2.jpg",new File(""));

   helper.setTo("[email protected]");
   helper.setFrom("[email protected]");

   mailSender.send(mimeMessage);
}

3 Timing tasks

In project development, we often need to perform some timing tasks. For example, we need to analyze the log information of the previous day in the early morning of each day. Spring provides us with a way to perform task scheduling asynchronously, and provides two interfaces
TaskExecutor interface
TaskScheduler interface and
two annotations :
@EnableScheduling
@Scheduled

Create a ScheduledService

package com.zs.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ScheduledService {
    
    

    //秒   分   时     日   月   周几
    @Scheduled(cron = "0 * * * * 0-7")
    public void hello(){
    
    
        System.out.println("hello.....");
    }
}

After writing the timing task here, we need to add @EnableScheduling to the main program to enable the timing task function

package com.zs;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableAsync //开启异步注解功能
@EnableScheduling //开启基于注解的定时任务
@SpringBootApplication
public class SprintbootTaskApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(SprintbootTaskApplication.class, args);
    }

}

cron expression

10/2 * * * * ?   表示每2秒 执行任务
(10 0/2 * * * ?   表示每2分钟 执行任务
(10 0 2 1 * ?   表示在每月的1日的凌晨2点调整任务
(20 15 10 ? * MON-FRI   表示周一到周五每天上午10:15执行作业
(30 15 10 ? 6L 2002-2006   表示2002-2006年的每个月的最后一个星期五上午10:15执行作
(40 0 10,14,16 * * ?   每天上午10点,下午2点,4点
(50 0/30 9-17 * * ?   朝九晚五工作时间内每半小时
(60 0 12 ? * WED   表示每个星期三中午12点
(70 0 12 * * ?   每天中午12点触发
(80 15 10 ? * *   每天上午10:15触发
(90 15 10 * * ?     每天上午10:15触发
(100 15 10 * * ?   每天上午10:15触发
(110 15 10 * * ? 2005   2005年的每天上午10:15触发
(120 * 14 * * ?     在每天下午2点到下午2:59期间的每1分钟触发
(130 0/5 14 * * ?   在每天下午2点到下午2:55期间的每5分钟触发
(140 0/5 14,18 * * ?     在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
(150 0-5 14 * * ?   在每天下午2点到下午2:05期间的每1分钟触发
(160 10,44 14 ? 3 WED   每年三月的星期三的下午2:102:44触发
(170 15 10 ? * MON-FRI   周一至周五的上午10:15触发
(180 15 10 15 * ?   每月15日上午10:15触发
(190 15 10 L * ?   每月最后一日的上午10:15触发
(200 15 10 ? * 6L   每月的最后一个星期五上午10:15触发
(210 15 10 ? * 6L 2002-2005   2002年至2005年的每月的最后一个星期五上午10:15触发
(220 15 10 ? * 6#3   每月的第三个星期五上午10:15触发

Guess you like

Origin blog.csdn.net/zs18753479279/article/details/112768673