cron expression parsing into java date

前端 未结 4 626
旧时难觅i
旧时难觅i 2021-02-08 02:38
  • my database having 10 18 16 ? * SUN,MON,WED,FRI * cron expression then how to convert into Java date.
  • how to comparing with present day time.
相关标签:
4条回答
  • 2021-02-08 03:00

    Please use:

    import org.springframework.scheduling.support.CronSequenceGenerator;
    
    final String cronExpression = "0 45 23 * * *";
    final CronSequenceGenerator generator = new CronSequenceGenerator(cronExpression);
    final Date nextExecutionDate = generator.next(new Date());
    

    ...and then I suggest use Joda DateTime for date comparison.

    0 讨论(0)
  • I wrote a small class for handling cron expressions, available here: https://github.com/frode-carlsen/cron

    Based on Joda-time, but should be fairly easy to port to Java8 time api. This also makes it possible to embed in unit tests, do simulations etc by adjusting the DateTime offset in Joda-time.

    It also has pretty good test coverage (was done as TDD Kata).

    Update Now supports java 8 time api as well thanks to a contribution from github user https://github.com/zemiak. In both cases, the expression parser is a single, tiny class which can easily be copied into your own project.

    0 讨论(0)
  • 2021-02-08 03:14

    Perhaps you can check cron-utils It has some utils to get next/previous execution given certain date, ex.: now. Works with JodaTime, but you could retrieve a JavaDate from there. The library is scheduler agnostic: you just provide a string with a cron expression. Is compatible with JDK6.

    0 讨论(0)
  • 2021-02-08 03:15

    You may want to look into the org.quartz.CronExpression class in the Quartz API.

    Please note that you cannot simply compare a cron expression with a date because the cron expression (typically) represents a sequence of various dates. In any case, you may find the following methods useful:

    public boolean isSatisfiedBy(Date date)
    public Date getNextValidTimeAfter(Date date)
    

    As for comparing two cron expressions, what would you like to compare? The only thing that IMO makes sense to compare are the next 'trigger' dates, i.e. dates obtained from getNextValidTimeAfter([some reference date]) calls.

    0 讨论(0)
提交回复
热议问题