SpringBoot实现运行时可动态修改的定时任务

本文介绍了在SpringBoot中如何实现在运行时动态修改定时任务的间隔,避免每次修改都需要重启服务器。通过分析Spring的CronTrigger和PeriodicTrigger源码,创建自定义ISchedule接口和SchedulingConfigurer实现类,实现了定时任务的动态调整。测试表明,该方法可以成功地按需求改变任务执行间隔。
摘要由CSDN通过智能技术生成

本文适用需求场景

原本使用cron表达式或fixedDelay/fixedRate的@Scheduled简单定时任务,但是间隔有时会改变,希望能运行时修改而无需每次更改代码和重启服务器

分析

scheduling-enable-annotation-support
根据文档,想实现更细粒度的控制,需要实现SchedulingConfigurer

@FunctionalInterface
public interface SchedulingConfigurer {
   
	void configureTasks(ScheduledTaskRegistrar taskRegistrar);
}

scheduling-trigger-implementations
想配置可动态修改的定时任务,需要实现自己的Trigger
原生的Trigger实现类只有CronTriggerPeriodicTrigger

CronTrigger部分源码

	private final CronExpression expression;

	private final ZoneId zoneId;
	@Override
	public Date nextExecutionTime(TriggerContext triggerContext) {
   
		Date date = triggerContext.lastCompletionTime();
		if (date != null) {
   
			Date scheduled = triggerContext.lastScheduledExecutionTime();
			if (scheduled != null && date.before(scheduled)) {
   
				// Previous task apparently executed too early...
				// Let's simply use the last calculated execution time then,
				// in order to prevent accidental re-fires in the same second.
				date = scheduled;
			}
		}
		else {
   
			date = new Date(triggerContext.getClock().millis());
		}
		ZonedDateTime dateTime = ZonedDateTime.ofInstant(date.toInstant(), <
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值