为什么不推荐使用Spring @Scheduled 中的 Cron 表达式

本文探讨了在Spring中使用@Scheduled注解定时任务时遇到的问题,特别是Cron表达式在时钟回拨时导致的任务失效。由于Scheduled Job的内部实现,无法直接修复,建议使用Cron4j等替代框架或者集中管理Scheduled Job,以便在出现问题时重启。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原因:

       Spring @Scheduled 使用非常方便,你只需要在指定执行定时任务的方法上添加 @Scheduled 注释即可,但是在最近用 @Scheduled 使用 Cron 表达式时,出现了大问题,问题如下:

       首先,时钟往过去拨,@Scheduled 的 Cron 表达式不会按预期执行了。(原因见后续源码分析)

       其次,Cron 不按预期执行了,Spring 也没有提供接口进行重启 Scheduled Job。

       最后,当系统庞大后,你无法追踪每一个 @Scheduled,当出现 Scheduled Job 失效后,你只能重启 JVM。

       造成 Scheduled Job 失效的原因,贴源码 org.springframework.scheduling.concurrent.ReschedulingRunnable:

	@Nullable
	public ScheduledFuture<?> schedule() {
		synchronized (this.triggerContextMonitor) {
			this.scheduledExecutionTime = this.trigger.nextExecutionTime(this.triggerContext);
			if (this.scheduledExecutionTime == null) {
				return null;
			}
			long initialDelay = this.scheduledExecutionTime.getTime() - System.currentTimeMillis();
			this.currentFuture = this.executor.schedule(this,
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值