Spring Boot Scheduling: @Scheduled Guide

The most common way to implement scheduling tasks in Spring Boot is by using the @Scheduled annotation.

The specific implementation steps are as follows:

  1. Add the @EnableScheduling annotation to the main class of the Spring Boot application to enable support for scheduled tasks.
  2. Adding the @Scheduled annotation to a method that needs to execute scheduled tasks specifies the rules for task execution, such as setting the trigger time, frequency, fixed delay, etc.
  3. If you need to pass parameters to a scheduled task method, you can inject the parameters into the class containing the scheduled task method, and then use the method name and parameters in the @Scheduled annotation to invoke it.

Here is an example of defining a scheduled task using the @Scheduled annotation.

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MyScheduledTask {

    // 每隔5秒执行一次任务
    @Scheduled(fixedRate = 5000)
    public void task1() {
        // 任务逻辑
    }

    // 每天凌晨1点执行任务
    @Scheduled(cron = "0 0 1 * * ?")
    public void task2() {
        // 任务逻辑
    }
}

In the examples above, two scheduled tasks methods were defined using the @Scheduled annotation. The task1 method runs every 5 seconds, while the task2 method runs once daily at 1 AM.

In addition to using the @Scheduled annotation, Spring Boot also offers other ways to implement scheduled tasks, such as implementing the SchedulingConfigurer interface or using ThreadPoolTaskScheduler. The specific choice depends on the project’s requirements and complexity.

bannerAds