典型用法
固定频率执行(fixedRate)
每隔固定时间执行一次任务,无论方法执行耗时多久。
📌 适用场景:轮询数据库、心跳检测、周期性上报等。
@Scheduled(fixedRate = 5000) // 每 5 秒执行一次
public void fixedRateTask() {
System.out.println("【fixedRate】当前时间:" + new Date());
}
固定延迟执行(fixedDelay)
上一次任务执行完成后,等待指定时间再执行下一次。
📌 适用场景:需要确保任务串行执行,避免并发问题。
@Scheduled(fixedDelay = 3000) // 上次执行完后延迟 3 秒
public void fixedDelayTask() {
System.out.println("【fixedDelay】当前时间:" + new Date());
try {
Thread.sleep(2000); // 模拟耗时操作
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
初始延迟(initialDelay)
首次执行前等待一段时间,之后按固定频率或延迟执行。
📌 适用场景:系统启动后需等待资源加载完成再开始执行任务。
@Scheduled(initialDelay = 10000, fixedRate = 5000) // 首次延迟 10 秒,之后每 5 秒执行
public void initialDelayTask() {
System.out.println("【initialDelay】当前时间:" + new Date());
}
使用 Cron 表达式(灵活调度)
使用标准的 Cron 表达式定义复杂的调度逻辑,例如每天凌晨执行、每周一执行等。
// 每天凌晨 1 点执行
@Scheduled(cron = "0 0 1 * * ?")
public void dailyTask() {
System.out.println("【cron】每日任务执行于:" + new Date());
}
// 每周一上午 9 点执行
@Scheduled(cron = "0 0 9 ? * MON")
public void weeklyTask() {
System.out.println("【cron】每周任务执行于:" + new Date());
}
多线程支持(默认单线程)
Spring 默认使用单线程执行所有定时任务。若希望并行执行多个任务,可自定义多线程调度器。
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
@Configuration
public class SchedulerConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(5);
taskScheduler.initialize();
taskRegistrar.setTaskScheduler(taskScheduler);
}
}