欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > Spring @Scheduled 典型用法

Spring @Scheduled 典型用法

2025/9/17 14:49:13 来源:https://blog.csdn.net/weixin_37646636/article/details/148723700  浏览:    关键词:Spring @Scheduled 典型用法

典型用法

固定频率执行(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 {@Overridepublic void configureTasks(ScheduledTaskRegistrar taskRegistrar) {ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();taskScheduler.setPoolSize(5);taskScheduler.initialize();taskRegistrar.setTaskScheduler(taskScheduler);}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词