Spring boot asynchronous task, scheduled task, mail task

Would you like pineapple crisp 2022-05-22 12:19:54 阅读数:118

springbootasynchronoustaskscheduled

Asynchronous task

Start the asynchronous task in the startup method class

@EnableAsync // Enable annotation based asynchronous task support 
@SpringBootApplication
public class AsyncApplication {

public static void main(String[] args) {

SpringApplication.run(AsyncApplication.class, args);
}
}

Use ( Use @Async Open asynchronous )

@Service
public class MyAsyncService {

/** * Simulate asynchronous task processing without return value * @throws Exception */
@Async
public void sendSMS() throws Exception {

System.out.println(" Calling SMS verification code service method ...");
Long startTime = System.currentTimeMillis();
Thread.sleep(5000);
Long endTime = System.currentTimeMillis();
System.out.println(" The execution of short message service takes time :" + (endTime - startTime));
}
/** * Simulate asynchronous task processing with return value * @return * @throws Exception */
@Async
public Future<Integer> processA() throws Exception {

System.out.println(" Start analyzing and counting business A data ...");
Long startTime = System.currentTimeMillis();
Thread.sleep(4000);
// The simulation defines a false statistical result 
int count=123456;
Long endTime = System.currentTimeMillis();
System.out.println(" Business A Data statistics take time :" + (endTime - startTime));
return new AsyncResult<Integer>(count);
}
@Async
public Future<Integer> processB() throws Exception {

System.out.println(" Start analyzing and counting business B data ...");
Long startTime = System.currentTimeMillis();
Thread.sleep(5000);
// The simulation defines a false statistical result 
int count=654321;
Long endTime = System.currentTimeMillis();
System.out.println(" Business B Data statistics take time :" + (endTime - startTime));
return new AsyncResult<Integer>(count);
}
}

call

@RestController
public class MyAsyncController {

@Autowired
private MyAsyncService myService;
@GetMapping("/sendSMS")
public String sendSMS() throws Exception {

Long startTime = System.currentTimeMillis();
myService.sendSMS();
Long endTime = System.currentTimeMillis();
System.out.println(" The main process takes time : "+(endTime-startTime));
return "success";
}
@GetMapping("/statistics")
public String statistics() throws Exception {

Long startTime = System.currentTimeMillis();
Future<Integer> futureA = myService.processA();
Future<Integer> futureB = myService.processB();
int total = futureA.get() + futureB.get();
System.out.println(" Asynchronous task data statistics summary results : "+total);
Long endTime = System.currentTimeMillis();
System.out.println(" The main process takes time : "+(endTime-startTime));
return "success";
}
}

Timing task

Start the scheduled task in the startup method class

@EnableScheduling // Enable annotation based scheduled task support 
@SpringBootApplication
public class AsyncApplication {

public static void main(String[] args) {

SpringApplication.run(AsyncApplication.class, args);
}
}

Use ( Use @Scheduled Turn on timed tasks 、 Start the project and execute it yourself )

@Service
public class ScheduledTaskService {

private static final SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private Integer count1=1;
private Integer count2=1;
private Integer count3=1;
@Scheduled(fixedRate = 60000)
public void scheduledTaskImmediately(){

System.out.println(String.format("finxedRate The first %s Execution times , The current time is :%s",count1++,dateFormat.format(new Date())));
}
@Scheduled(fixedDelay = 60000)
public void scheduledTaskAfterSleep() throws InterruptedException {

System.out.println(String.format("fixedDelay The first %s Execution times , The current time is :%s",count2++,dateFormat.format(new Date())));
Thread.sleep(10000);
}
@Scheduled(cron = "0 * * * * *")
public void scheduledTaskCron(){

System.out.println(String.format("cron The first %s Execution times , The current time is :%s",count3++,dateFormat.format(new Date())));
}
}

@Scheduled Note that

attribute explain
cron Be similar to cron The expression of , You can customize the seconds triggered by timed tasks 、 minute 、 Hours 、 The day of the month 、 month 、 The day of the week
zone Appoint cron The time zone in which the expression will be resolved . By default , The attribute is an empty string ( That is, use the local time zone of the server )
fixedDelay Means to continue to execute the next task after the specified time after the execution of the last task ( The property value is long type )
fixedDelayString It means to continue to execute the next task after the specified time after the last task execution - - missions ( The property value is long String form of type )
fixedRate Indicates that the task is executed every specified time ( The property value is long type )
fixedRateString Indicates that the task is executed every specified time ( The property value is long String form of type )
initialDelay It means that fixedRate or fixedDelay The first time the task is performed The number of milliseconds to delay before ( The property value is long type )
initialDelayString It means that fixedRate or fixedDelay The first time the task is performed The number of milliseconds to delay before ( The property value is long String form of type )

cron attribute
Specify in detail the seconds of scheduled task execution 、 branch 、 Hours 、 Japan 、 month 、 week .@Scheduled(cron = "0 * * * * *")
cron Introduction to attribute field values

Field Value for Special characters allowed
second 0~59, - * /
branch 0~59, - * /
Hours 0~23, - * /
Japan 1~31, - * / ? L
month 1~12、 Month corresponds to... Before English 3 Letters ( Case equal ), - * / ?
week 0~7 (0 and 7 Express SUN)、 Week corresponds to English before 3 Letters ( Case equal )
MON-FRI It means Monday to Friday
, - * / ? L

cron Introduction to special characters of attribute field value

Special characters explain Example
, Represents enumeration @Sheduled(cron="1,3,5 * * * * * ") Indicates any time 1、3、5 Every second
- Indicates the interval @Sheduled(cron="0 0-5 14 * * ? ") Every afternoon 2:00-2:05 period , Every time 1 Minutes to trigger
* Can take any value @Scheduled (cron=“0 0 12 * * ?” ) At noon every day 12:0 Trigger once
/ Indicating step size @Scheduled(cron= “0/5 * * * * *”) It means starting from the whole second of any time , every other 5 Every second
? Japan / Week conflict match @Scheduled(cron=“0 * * 26 * ?”) Represents the 26 Every minute of the day
L Last @Scheduled(cron= “0 0 * L * ?”) Means to execute every hour on the last day of each month

Email tasks

Add mail service dependent initiator

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

Add mail configuration

spring:
mail:
host: smtp.qq.com # Email server address 
username: [email protected] # Email account 
password: xxxxxxxxxxxxxxxx # Authorization code 
default-encoding: utf-8 # Default encoding 

send out

Easy to use

@Autowired
JavaMailSender mailSender;
// Read the sender of the configuration file 
@Value("${spring.mail.username}")
private String from ;
@Test
public void sendEmail(){

// Automatic assembly is not necessary new 了 
//MailSender mailSender = new JavaMailSenderImpl();
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
// Sender 
simpleMailMessage.setFrom(from);
// The content of the message is 
simpleMailMessage.setText(" I wish you happiness ");
// To whom? 
simpleMailMessage.setTo("[email protected]");
// Email subject 
simpleMailMessage.setSubject(" test ");
mailSender.send(simpleMailMessage);
}

send out html Format message

@Autowired
JavaMailSender mailSender;
// Read the sender of the configuration file 
@Value("${spring.mail.username}")
private String from ;
@Test
public void sendHTMLEmail() throws MessagingException {

MimeMessage mimeMessage = mailSender.createMimeMessage();
// here multipart Must be set to true
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
mimeMessageHelper.setFrom(from);
// here true For parsing html label , Set to false Don't take effect 
mimeMessageHelper.setText("<h1> This is a letter html Format message </h1>",true);
mimeMessageHelper.setTo("[email protected]");
mimeMessageHelper.setSubject(" test html Format mail ");
mailSender.send(mimeMessage);
}

It can also be used here Thymeleaf Template instead of

  • introduce Thymeleaf rely on
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
  • establish email.html file
    <!DOCTYPE html>
    <html lang="zh" xmlns:th="http://www.thymeleaf.org">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body>
    <div>
    <span th:text="${username}"></span> Hello
    </div>
    <div>
    Your verification code is :<span th:text="${code}"></span>
    </div>
    </body>
    </html>
    
  • send out
    @SpringBootTest
    class EmailApplicationTests {
    
    @Test
    void contextLoads() {
    
    }
    @Autowired
    private JavaMailSender mailSender;
    // Read the sender of the configuration file 
    @Value("${spring.mail.username}")
    private String from ;
    @Autowired
    private TemplateEngine templateEngine;
    @Test
    public void sendHTMLEmail() throws MessagingException {
    
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    // here multipart Must be set to true
    MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
    mimeMessageHelper.setFrom(from);
    // by email.html Set values and generate String String of type 
    Context context = new Context();
    context.setVariable("username"," Honest man ");
    context.setVariable("code","456123");
    String email=templateEngine.process("email",context);
    // here true For parsing html label , Set to false Don't take effect 
    mimeMessageHelper.setText(email,true);
    mimeMessageHelper.setTo("[email protected]");
    mimeMessageHelper.setSubject(" test html Format mail ");
    mailSender.send(mimeMessage);
    }
    }
    

Send email with attachments

@Autowired
JavaMailSender mailSender;
// Read the sender of the configuration file 
@Value("${spring.mail.username}")
private String from ;
@Test
public void testSendFileEmail() throws MessagingException {

MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setTo("[email protected]");
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setText(" A selfie ");
FileSystemResource fileSystemResource = new FileSystemResource(new File(" File path "));
mimeMessageHelper.addAttachment("mhb.jpg",fileSystemResource);
mimeMessageHelper.setSubject(" This is a HTML mail ");
mailSender.send(mimeMessage);
}

obtain Authorization code

 Please add a picture description
 Please add a picture description

copyright:author[Would you like pineapple crisp],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/142/202205211817461833.html