2024.6.5 Wednesday
Following 【WEEK15】 【DAY2】【DAY3】Email Tasks【English Version】
Contents
- 17. Asynchronous, Scheduled, and Email Tasks
- 17.3. Scheduled Tasks
- 17.3.1. Two Annotations:
- 17.3.2. Cron Expression
- 17.3.3. Modify Springboot09TestApplication.java to Enable Scheduling
- 17.3.4. Create ScheduledService.java
- 17.3.5. Restart the Project
17. Asynchronous, Scheduled, and Email Tasks
17.3. Scheduled Tasks
In project development, it is often necessary to execute some scheduled tasks, such as analyzing the previous day’s log information at midnight every day. Spring provides us with asynchronous task scheduling methods, offering two interfaces (see TaskExecutor.class and TaskScheduler.class for details).
- TaskExecutor interface (Task Executor)
- TaskScheduler interface (Task Scheduler)
17.3.1. Two Annotations:
- @EnableScheduling——Annotation to enable scheduling
- @Scheduled——When to execute
17.3.2. Cron Expression
Cron Expression:
Field | Allowed Values | Allowed Special Characters |
---|---|---|
Second | 0-59 | , - * / |
Minute | 0-59 | , - * / |
Hour | 0-23 | , - * / |
Day | 1-31 | , - * / ? L W C |
Month | 1-12 | , - * / |
Week | 0-1 or SUN-SAT 0,7 is SUN | , - * / ? L W C |
Special Character | Meaning |
---|---|
, | Enumeration |
- | Range |
* | Any |
/ | Step |
? | Day/Week conflict match |
L | Last |
W | Weekday |
C | Value calculated after calendar practice |
# | Week, 4#2 means the second Wednesday of the month |
17.3.3. Modify Springboot09TestApplication.java to Enable Scheduling
package com.P51;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableAsync // Enable asynchronous annotation functionality
@EnableScheduling // Enable scheduling annotation functionality
@SpringBootApplication
public class Springboot09TestApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot09TestApplication.class, args);
}
}
17.3.4. Create ScheduledService.java
package com.P51.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ScheduledService {
// Cron expression (you can search for explanations online)
@Scheduled(cron = "30 06 14 * * ?") // Execute once daily at 14:06:30
@Scheduled(cron = "0/2 * * * * ?") // Execute every two seconds daily
public void hello(){
System.out.println("execute");
}
}
Official explanation, very detailed and worth reading:
Other references:
https://www.bejson.com/othertools/cron/