How to use scheduled tasks in Spring Boot?
Using scheduled tasks in Spring Boot is very simple. You just need to define a method in a class annotated with @Component or @Service, and then use the @Scheduled annotation to mark that method. Here are the specific steps:
- Create a class and annotate it with @Component or @Service to make it a Spring Bean.
@Component
public class MyScheduledTask {
@Scheduled(fixedRate = 5000) // 每隔5秒执行一次
public void myTask() {
// 执行定时任务的逻辑
System.out.println("定时任务执行中...");
}
}
- Add the “@Scheduled” annotation to the method that needs to be executed on a regular schedule and configure the execution rules for the scheduled task.
@Scheduled(cron = "0 0 0 * * ?") // 每天凌晨执行
public void myTask() {
// 执行定时任务的逻辑
System.out.println("定时任务执行中...");
}
- Configure the thread pool size and other related configurations for scheduled tasks in the application.properties or application.yml configuration file.
# 定时任务线程池大小
spring.task.scheduling.pool.size=10
- “When you start the Spring Boot application, the scheduled tasks will be executed according to the set rules.”
In general, using scheduled tasks in Spring Boot is very convenient, requiring only simple configuration to implement the execution of tasks on a schedule.