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

Viewed 703

I have a scheduled task in a spring boot application:

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

With a corresponding test:

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

Now I want to use a cron instead of a fixed rate:

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

Now I need to adapt the test to this. How do get a Duration object corresponding to the frequency of the cron expression?

1 Answers

Spring specific solution:

Spring provides a CronSequenceGenerator which can be used to parse a cron expression and get the next Date instance at which it will be triggered after the provided Date.

So to get a 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()
);
Related