3

I have an initial date and a cron expression. How could I find the next date satisfying this cron expression ?.

    String cronExpresion = "* * * * * *"
    LocalDateTime initial = LocalDateTime.now()
    LocalDateTime next = ?

I tried CronSequenceGenerator and its next() method but it uses java.util.Date and I would prefer not to convert LocalDateTime to Date and vice versa. Plus, I've got different result (time between the 2 dates) from several run with a cron like 'every 10 secondes' ...

Any idea ? lib ?

gnos
  • 796
  • 1
  • 6
  • 17
  • 2
    Have you already looked into this project: https://github.com/frode-carlsen/cron ? – Rlarroque May 22 '17 at 09:52
  • @Rlarroque not sure I am allowed to use "non-official" kind of library.. unless I remake it by myself, but I'll look into it :) – gnos May 22 '17 at 10:13
  • 1
    I think implementing an algorithm that do this would be too broad for SO, but library recommendations are off-topic here. If you are already using a specific library, you could narrow the question down to that library (edit the question and tags) and get an appropriate answer. Otherwise this question will probably get closed. – Didier L May 22 '17 at 11:46

3 Answers3

4

Omnicron (https://github.com/intelie/omnicron) seems to satisfy at least some of your requirements:

Cron cron = new Cron("*/5 * * * *");
ZonedDateTime date = ZonedDateTime.now();

System.out.println("Next execution: " + cron.next(date));
System.out.println("Prev execution: " + cron.prev(date));

(Cron::next and Cron::prev accept any Temporal value, not just ZonedDateTime.)

Aside from that, Omnicron is, as a bonus, compatible with Spring's CronSequenceGenerator (https://github.com/intelie/omnicron/blob/master/src/test/java/net/intelie/omnicron/SpringCompatibilityTest.java)

srborlongan
  • 4,460
  • 4
  • 26
  • 33
2

Another solution is to use CronSequenceGenerator from spring.

String cronExpresion = "* * * * * *";
Date next = new CronSequenceGenerator().next(new Date());
return LocalDateTime.ofInstant(next.toInstant(), ZoneId.systemDefault());
Philip John
  • 5,275
  • 10
  • 43
  • 68
0

Finally Spring with version 5.3.0 published new version of CronExpression which is not connected to old java time API

newOne
  • 679
  • 2
  • 9
  • 27