如何从 cron 表达式中获取 Java 持续时间?

How do I get a Java Duration from a cron expression?

我在 spring 启动应用程序中有一个计划任务:

@Scheduled(fixedRateString = "${scheduled.task.rate}")
public void runScheduledTask() {
    // ...
}

有相应的测试:

@Test
public void test_scheduledTask_runs() {
    await().atMost(Duration.ofMillis(scheduledTaskRate).multipliedBy(2)).untilAsserted(() -> {
        Mockito.verify(scheduledTasks, Mockito.atLeastOnce()).runScheduledTask();
    });
}

现在我想使用 cron 而不是固定速率:

@Scheduled(cron = "${scheduled.task.cron}")

现在我需要根据这个调整测试。如何得到一个Duration对应于cron表达式频率的对象?

Spring具体解决方案:

Spring 提供了一个 CronSequenceGenerator which can be used to parse a cron expression and get the next Date 实例,它将在提供的 Date.

之后被触发

所以得到一个Duration:

CronSequenceGenerator generator = new CronSequenceGenerator(scheduledTaskCron);
Date nextExecution = generator.next(new Date());
Date nextToNextExecution = generator.next(nextExecution);
Duration durationBetweenExecutions = Duration.between(
        nextExecution.toInstant(), nextToNextExecution.toInstant()
);