Technology Sharing

SpringBoot Daily: @Scheduled is executed once when the service starts

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina


When it comes to scheduled tasks, we should think of @Scheduled, Quartz and XXL-JOB, but some single services or small projects may directly use @Scheduled to implement asynchronous tasks for convenience and speed. Therefore, the theme requirements of this article are extended.

When using @Scheduled in a project, how can we execute the specified asynchronous task in advance when the project starts?

1. @Scheduled Detailed Explanation

The @Scheduled annotation supports multiple parameters for flexible control of task execution time

  • cron: Cron expression, which can accurately control seconds, minutes, hours, days, months, weeks, etc.
    insert image description here
  • zone: Receives a time zone, such as the time zone Asia/Shanghai that we generally use. We usually leave this field blank.
  • fixedDelay: how long after the last execution to wait before executing again. For example, @Scheduled(fixedDelay = 5000)
  • fixedDelayString: Same as fixedDelay, but in string format. The only difference is that it supports placeholders, such as @Scheduled(fixedDelayString = "5000")
  • fixedRate: how long after the last execution time to execute again, such as @Scheduled(fixedRate = 5000)
  • fixedRateString: Same as fixedRate, but in string format. The only difference is that it supports placeholders.
  • initialDelay: How long to delay the first time before executing. For example, the first time it is executed after a delay of 1 second, and then it is executed every 5 seconds according to the fixedRate rule @Scheduled(initialDelay=1000, fixedRate=5000)
  • initialDelayString: Same as initialDelayString, but in string format. The only difference is that it supports placeholders.

2. Logical Implementation

1. Create a scheduled task logic method

/**
 * @Author 码至终章
 * @Version 1.0
 */
@Component
public class ScheduledTest {

    @Scheduled(cron = "* 1 * * * ?")
    public void task1() throws Exception{
        System.out.println("task1 执行: " + Thread.currentThread() + "-" + DateTime.now());
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

2. Create a new startup execution class

This class mainly calls the specified task method manually at startup

/**
 * @Author 码至终章
 * @Version 1.0
 */
@Component
public class StartupTasks {

    private final ScheduledTest scheduledTasks;

    public StartupTasks(ScheduledTest scheduledTasks) {
        this.scheduledTasks = scheduledTasks;
    }

    @PostConstruct
    public void startUp() {
        try {
            System.out.println("服务启动执行任务");
            scheduledTasks.task1();
        }catch (Exception e){
			e.printStackTrace();
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

Note: Remember to add @EnableScheduling to the startup class so that the scheduled task will be executed. Of course, this does not affect the logical test of this article

3. Test Results

After the service is started, check the print information
insert image description here