某退休程序猿的工作日志
本文适用需求场景
原本使用cron表达式或fixedDelay/fixedRate的@Scheduled简单定时任务,但是间隔有时会改变,希望能运行时修改而无需每次更改代码和重启服务器
分析
scheduling-enable-annotation-support
根据文档,想实现更细粒度的控制,需要实现SchedulingConfigurer
@FunctionalInterface
public interface SchedulingConfigurer {
void configureTasks(ScheduledTaskRegistrar taskRegistrar);
}
scheduling-trigger-implementations
想配置可动态修改的定时任务,需要实现自己的Trigger
类
原生的Trigger
实现类只有CronTrigger
、PeriodicTrigger
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(), <