quartz scheduler – cron expression parsing into java date

quartz scheduler – cron expression parsing into java date

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.

I wrote a small class for handling cron expressions, available here:

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).

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.

quartz scheduler – cron expression parsing into java date

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.

Leave a Reply

Your email address will not be published. Required fields are marked *