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

使用ScheduledThreadPoolExecutor创建定时任务

现象

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

解决

  1. 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();
            }
        }
    }
  1. 只能先修改时间再创建定时任务就可以解决问题。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容