0%

spring定时任务修改系统时间后未生效

文章字数:191,阅读全文大约需要1分钟

使用ScheduledThreadPoolExecutor创建定时任务

现象

  1. 创建定时任务之后修改系统时间,以自测定时任务是否执行。发现未执行
  2. 不修改系统时间则正常

解决

  1. DelegatingErrorHandlingRunnable.class可以看到每次执行之后才会使用延时创建下一个时段的任务。所以即使是cron表达式创建的定时任务指定了下一次执行时间后就和系统时间没有关联了。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    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();
    }
    }
    }
  2. 只能先修改时间再创建定时任务就可以解决问题。