问题
- 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.
- and one more is how to compare to cron expressions i.e.
10 18 16 ? * SUN,MON,WED,FRI *
and0 30 9 30 * ?
- please explain the sample code using quartz or spring scheduling.
回答1:
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.
回答2:
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.
回答3:
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.
回答4:
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.
来源:https://stackoverflow.com/questions/23835171/cron-expression-parsing-into-java-date