The selection

There are two ways to use scheduled tasks in Spring Boot:

  • scheduled
  • quartz

In my opinion, we only need to consider the following aspects:

  • Very simple Scheduled tasks -> @scheduled annotations
  • Scheduling is complicated -> Quartz
  • The task requires non-blocking -> Quartz
  • Distributed -> Quartz

All right, just the simplest tasks scheduled, the more complicated ones quartz

The scheduled changes have applied in quartz

scheduled

Enabling a Scheduled Task

All we need to do is add @enablesCheduling annotations to the startup class

@EnableScheduling
@SpringBootApplication
public class Application {
  /** * main method **@paramThe args parameter * /
  public static void main(String[] args) { SpringApplication.run(Application.class, args); }}Copy the code

Writing a scheduled Task

We just need to add the @scheduled annotation to the method:

public class Task {

    @Scheduled(cron="0/5 * * * * ? ")
    public void run(a) {
        // Task logic}}Copy the code

The details of the parameters in the @scheduled annotation can be read in this document

Here in particular to explain the use of the need to pay attention to the following points:

  1. “0/5 * * * *? “, is every five seconds, but from the hour, i.e. 0/5/10/15 per minute… Do it sequentially, not from the moment you start the project

  2. To start the project, use the fixedDelay parameter, such as @scheduled (fixedDelay=5000). The value is millisecond, that is, start the next task 5 seconds after the last one

  3. The fixedDelayString argument supports SpEL expressions in milliseconds to make the task time configurable, such as @scheduled (fixedDelayString = “${task.interval}”).