使用
ScheduledThreadPoolExecutor
创建定时任务
现象
- 创建定时任务之后修改系统时间,以自测定时任务是否执行。发现未执行
2.不修改系统时间则正常
解决
-
DelegatingErrorHandlingRunnable.class
可以看到每次执行之后才会使用延时创建下一个时段的任务。所以即使是cron
表达式创建的定时任务指定了下一次执行时间后就和系统时间没有关联了。
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, initialDelay, TimeUnit.MILLISECONDS);
return this;
}
}
@Override
public void run() {
Date actualExecutionTime = new Date();
super.run();
Date completionTime = new Date();
synchronized (this.triggerContextMonitor) {
this.triggerContext.update(this.scheduledExecutionTime, actualExecutionTime, completionTime);
if (!this.currentFuture.isCancelled()) {
schedule();
}
}
}
- 只能先修改时间再创建定时任务就可以解决问题。