Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring调度配置器动态延迟_Java_Spring_Cron_Scheduler - Fatal编程技术网

Java Spring调度配置器动态延迟

Java Spring调度配置器动态延迟,java,spring,cron,scheduler,Java,Spring,Cron,Scheduler,我有一个应用程序,应该在每天早上7点到晚上7点之间做一次。我想随机选择一个有效的时间来运行任务,然后为下一个任务使用不同的开始时间 我找到的每个解决方案都会生成一个有效的随机启动cron,但之后每次运行都会生成相同的cron。每次我都需要一个不同的,随机的开始 我尝试使用CronTrigger,但结果仍然是常量。下面是一些示例代码: @Component public class ScheduledTasks implements SchedulingConfigurer { privat

我有一个应用程序,应该在每天早上7点到晚上7点之间做一次。我想随机选择一个有效的时间来运行任务,然后为下一个任务使用不同的开始时间

我找到的每个解决方案都会生成一个有效的随机启动cron,但之后每次运行都会生成相同的cron。每次我都需要一个不同的,随机的开始

我尝试使用CronTrigger,但结果仍然是常量。下面是一些示例代码:

@Component
public class ScheduledTasks implements SchedulingConfigurer {

  private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);
  private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

  @Override
  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    taskRegistrar.setScheduler(this.taskExecutor());
    taskRegistrar.addTriggerTask(
      () -> logger.info("The time is {}", dateFormat.format(new Date())),
      new CronTrigger(this.randomCron(0, 60)));
  }

  public Executor taskExecutor() {
    return Executors.newScheduledThreadPool(5);
  }

  private String randomCron(int min, int max) {
    return ThreadLocalRandom.current().nextInt(min, max) + " * * * * *";
  }
}
我了解了春季跑步,你可以用它来安排下一次跑步。现在,我的新代码如下所示:

  @Override
  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    taskRegistrar.setScheduler(this.taskExecutor());
    taskRegistrar.addTriggerTask(
      () -> logger.info("The time is {}", dateFormat.format(new Date())),
      (tc) -> {
        Date lastCompletion = tc.lastCompletionTime();
        if (lastCompletion == null) {
          lastCompletion = new Date();
        }
        Calendar cal = new Calendar.Builder().setInstant(lastCompletion).build();
        int second = ThreadLocalRandom.current().nextInt(0, 60);
        long minute = 60000L + second * 1000L;
        Date nextRun = new Date(cal.getTime().getTime() + minute);
        logger.info("Next run will be at {}", nextRun);
        logger.info("Time between runs is {}", minute);
        return new Date();
      });
  }