[springboot2.1.x @Scheduled timer, asynchronous start]

1. Scheduled task

A program executed at a specified time.
Usage scenario

  1. Data analysis
  2. Data cleaning
  3. System service monitoring

2. Synchronous and asynchronous

Synchronous call

  • The program is executed in sequence according to the code sequence, and each line of program must wait for the execution of the previous line of program before execution;

Asynchronous call (asynchronous means that threads and threads do not wait)

  • During sequential execution, the following program is executed without waiting for the return result of the code block called asynchronously.

App.java

@SpringBootApplication
@EnableScheduling // Start timer
@EnableAsync // Support asynchronous timer
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

application.xml

spring:
  task:
    # Spring executor configuration, corresponding to TaskExecutionProperties configuration class. For spring asynchronous tasks, this executor is used.
    execution:
      thread-name-prefix: async- # The prefix of the thread name of the thread pool. The default is task -, which is recommended to be set according to your application
      pool: # Thread pool correlation
        core-size: 8 # The number of core threads, the number of threads initialized when the thread pool is created. The default is 8.
        max-size: 20 # The maximum number of threads, the maximum number of threads in the thread pool. Only when the buffer queue is full, will threads exceeding the number of core threads be applied. The default is integer MAX_ VALUE
        keep-alive: 60s # The idle time of a thread is allowed. When it exceeds the idle time of a thread other than the core thread, it will be destroyed after the idle time arrives. The default is 60 seconds
        queue-capacity: 200 # Buffer queue size, which is used to buffer the size of the queue executing tasks. The default is integer MAX_ VALUE . 
        allow-core-thread-timeout: true # Whether to allow the core thread to time out, that is, to enable the dynamic growth and reduction of the thread pool. The default is true.
      shutdown:
        await-termination: true # Whether to wait for scheduled task execution to complete when the application is closed. The default value is false. It is recommended to set it to true
        await-termination-period: 60 # The maximum time to wait for a task to complete, in seconds. The default value is 0, which can be set according to your application

ScheduleTask.java

@Slf4j
@Component
public class ScheduleTask {

    @Scheduled(cron = "0/1 * * * * *")
    public void synTask() {
        sleep();
        System.out.println(Thread.currentThread().getName() + " syn-task implement,current time : " + LocalDateTime.now());
    }
 
    @Async
    @Scheduled(cron = "0/1 * * * * *")
    public void asyncTask() {
        sleep();
        System.out.println(Thread.currentThread().getName() + " async-task implement,current time : " + LocalDateTime.now());
    }
 
    private void sleep() {
        try {
            Thread.sleep(10 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Timer execution rule annotation

@Scheduled(fixedRate = 5000) : Execute again 5 seconds after the last execution time point
@Scheduled(fixedDelay = 5000) : Execute again 5 seconds after the last execution time point
@Scheduled(initialDelay=1000, fixedRate=5000) : Execute after the first delay of 1 second, and then press fixedRate The rule is executed every 5 seconds
@Scheduled(cron="/5") : adopt cron Expression definition rules

Detailed explanation of cron expression

cron expressions have at least six (and possibly seven) space separated time elements.

Format: cron = [Second] [minute] [hour] [day] [month] [week (week)] [year]

Serial numberelementvaluewildcard
1second0-59- * /
2minute0-59- * /
3hour0-23- * /
4day1-31- * ? / L W
5month1-12 or JAN-DEC,- * /
6Week (week)1~7 1=SUN or SUN, MON, TUE, WED, THU, FRI, SAT,- * ? / L #
7particular year1970-2099,- * /

Wildcard explanation

Serial numberwildcardremarks
1*Indicates all values. For example, if the position of second is *, it means that it will be executed every second
2?Indicates that no value is specified. For example, the position of year is?, It means you don't know a certain year
3-Indicates the interval. For example, if the bit of the hour is 1-2, it means that the hour is 1 and 2 will be executed
4,Indicates that multiple values are specified. For example, it will run when the hour is 1, 2 and 3
5LThe last minute of every hour will run at the last minute
6WIndicates the nearest working day from the specified date. For example, 10W represents the nearest working day from the 10th
7#Indicates the number of days. For example, 2#3 represents the third week of February

The following is a common corn expression:

expressionremarks
*/5 * * * * ?Every 5 seconds
0 */1 * * * ?Every 1 minute
0 0 23 * * ?Every day at 23:00
0 0 1 1 * ?Once at 1 a.m. on the 1st of each month
0 0 23 L * ?At 23:00 on the last day of each month
0 0 1 ? * LOnce every Sunday at 1 a.m
0 15,25,35 * * * ?Once at 15, 25 and 35 points
0 * 16 * * ?Every day from 16 o'clock to 16:59 p.m
0 0/5 16 * * ?Trigger every 5 minutes between 16:00 p.m. and 16:55 p.m
0 0/5 14,18 * * ?Triggered every 5 minutes between 14:00 p.m. and 14:55 p.m. and between 18:00 p.m. and 18:55 p.m
0 0-5 14 * * ?Every day from 14:00 PM to 14:05 PM
0 10,44 14 ? 3 WEDEvery Wednesday in March every year at 14:10 p.m. and 14:44 p.m
0 15 10 ? * MON-FRI10:15 every weekday
0 15 10 15 * ?At 10:15 a.m. on the 15th of every month
0 15 10 L * ?At 10:15 on the last day of each month
0 15 10 ? * 6LAt 10:15 on the last Friday of each month
0 15 10 ? * 6LEvery Friday to the last month of 2002-2005
0 15 10 ? * 6#3At 10:15 on the third Friday of each month
0 0 12 1/5 * ?Every month from the first day, it is triggered every five days at 12 noon
0 11 11 11 11 ?At 11:11 on November 11 every year
0 0 0,13,18,21 * * ?At 0:00, 13:00, 18:00 and 21:00 every day
0 0/30 9-17 * * ?Every half an hour during nine to five working hours
0 0 12 * * ?Triggered at 12 noon every day
0 15 10 ? * *Triggered every morning at 10:15
0 0 23 * * ?Every day
0 59 23 ? * SUNweekly
0 59 23 L * ?monthly
0 59 23 L 3,6,9,12 ?Quarterly
0 0 0 31 12 ?annually

Keywords: Java Spring

Added by dsainteclaire on Tue, 22 Feb 2022 11:55:59 +0200