spring boot 2.x deep understanding of scheduled task schedule

Posted by ticallian on Thu, 23 Dec 2021 20:17:08 +0100

Look first spring boot 2. X actor monitoring / health check / audit / statistics

Based on the above code modification

Source code: https://github.com/langyastudio/langya-tech/tree/springboot/scheduling

Official documents: https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#scheduling-annotation-support

In many applications, it is often necessary to perform scheduled tasks. For example, send reports to users every day, regularly check the system status, etc. In Spring + spring MVC environment, generally speaking, there are two schemes to implement scheduled tasks:

  • One is to use the @ Scheduled annotation of Spring's own timed task processor
  • The other is to use a third-party framework such as Quartz

Spring's own solution

Spring has built-in support for timed tasks and Cron tasks, so you don't need to write a lot of code. You only need to use two annotations:

  • Enable support for scheduled tasks through @ enableshcheduling (based on class annotation)

  • Use @ Scheduled to annotate the tasks to be Scheduled (based on function annotation)

Scheduled

Specific steps:

Add @ enablesscheduling to enable support for scheduled tasks:

@SpringBootApplication
@EnableScheduling
public class Application
{
    public static void main(String[] args)
    {
       ...
    }
}

Next, define the class of the Scheduled task (Mark @ Component) and annotate the Scheduled task with @ Scheduled:

@Log4j2
@Component
public class SchedulingService
{
    @Scheduled(fixedRate = 60000)
    public void  fixedRateSchedule()
    {
        log.info("Every 60 seconds fixedRateSchedule...");
    }


    /**
     * initialDelay The task starts after a delay of 5 seconds
     */
    @Scheduled(initialDelay = 5000, fixedDelay = 10000)
    public void  fixedDelaySchedule()
    {
        log.info("Execute 10 seconds after the last task is completed fixedDelaySchedule...");
    }
}

Description of key parameters:

  • fixedRate

    Execute every fixed time, regardless of whether the last task is completed or not

  • fixedDelay

    After the last task execution, execute the new task after the specified time

  • initialDelay

    Indicates the delay time for the first task start

  • All time is in milliseconds

For example, the annotation of the fixedDelaySchedule function above specifies that the startup delay is 5 seconds and the task is executed at an interval of 10 seconds. You can see the log printed by the scheduled task on the console:

2021-08-16 18:30:14.729 INFO [scheduling-1] com.langyastudio.springboot.common.middleware.task.SchedulingService : Execute 10 seconds after the last task is completed fixedDelay...
2021-08-16 18:30:24.730 INFO [scheduling-1] com.langyastudio.springboot.common.middleware.task.SchedulingService : Execute 10 seconds after the last task is completed fixedDelay...
2021-08-16 18:30:34.732 INFO [scheduling-1] com.langyastudio.springboot.common.middleware.task.SchedulingService : Execute 10 seconds after the last task is completed fixedDelay...

Dynamically modify parameter values:

For example, fixedDelay=10000. What if it is changed to 60 seconds according to the actual situation? Can it only be recompiled?

You can see that the Scheduled annotation provides parameters such as fixedDelayString, fixedRateString and initialDelayString. You can put the configuration value of Scheduled tasks into the configuration file, so as to dynamically modify the Scheduled task time.

For example, define a profile:

langyastudio:
  task:
    fixedDelaySchedule: 60000

Then, the purpose of dynamically modifying parameter values is realized by replacing xxx with xxxString:

@Scheduled(initialDelay = 5000, fixedDelayString = "${langyastudio.task.fixedDelaySchedule:10000}")
public void  fixedDelaySchedule()
{
    log.info("Execute 10 seconds after the last task is completed fixedDelay...");
}

The fixedDelayString mentioned above means that langyastudio is obtained from the configuration file first task. Fixeddelayschedule value. If not, the default value of 10000 is used.

Scheduled task configuration:

Examples are as follows:

spring:
  task:
    scheduling:
      pool:
        size: 5        
      shutdown:
        #When closing the application, do you want to wait for the task to complete
        await-termination: true
        await-termination-period: 60000 

By configuring parameters, you can customize the measures adopted by the planned task when the application is closed. For example, await termination means to wait until the execution is completed before closing.

Cron

Cron originates from the crond daemon of Unix/Linux system. It defines the task trigger time in a concise expression (triggered by time, which is different from repeatedly scheduled tasks).

Recommend an online Cron expression generator: https://crontab.guru/

In Spring, Cron expressions can be used to perform Cron tasks. Its format is as follows:

 ┌───────────── second (0-59)
 │ ┌───────────── minute (0 - 59)
 │ │ ┌───────────── hour (0 - 23)
 │ │ │ ┌───────────── day of the month (1 - 31)
 │ │ │ │ ┌───────────── month (1 - 12) (or JAN-DEC)
 │ │ │ │ │ ┌───────────── day of the week (0 - 7)
 │ │ │ │ │ │          (0 or 7 is Sunday, or MON-SUN)
 │ │ │ │ │ │
 * * * * * *
  Second minute hour day month week year 

The specific values are as follows:

Serial numberexplainRequiredAllowed valuesWildcards allowed
1secondyes0-59- * /
2branchyes0-59- * /
3Timeyes0-23- * /
4dayyes1-31- * ? / L W
5monthyes1-12 or JAN-DEC- * /
6weekyes1-7 or SUN-SAT- * ? / L #
7yearno1970-2099- * /

Example:

Cron expression executed at 12:00 from Monday to Friday:

0 0 12 * * MON-FRI

Cron expression executed at 12:00 on the 1st-3rd and 10th of each month:

0 0 12 1-3,10 * *

Define a task to be executed every 30 seconds in spring:

@Scheduled(cron = "*/30 * * * * *")
public void  cronchedule()
{
    log.info("Every 30 seconds cron...");
}

At this time, xx:xx:00 and xx:xx:30 perform the above tasks

cron can also use configuration files, which will not be described in detail

Quartz

Using timed tasks and Cron tasks in Spring is very simple, but note that these tasks are scheduled in each JVM process. If two processes are started locally or applications are started on multiple machines, the scheduled tasks and Cron tasks of these processes run independently and do not affect each other.

If some scheduled tasks are to be run in a cluster, such as the inspection task at 23:00 every day, only one of them in the cluster is required to run, which can be considered at this time Quartz.

Quartz can configure a JDBC data source to store all task scheduling plans and task execution status. For details on quartz integration, please refer to Spring documentation.

Topics: Spring cron