Cronexation analysis on java date

  • my database has (10 18 16? * SUN, MON, WED, FRI *) cron expression, then how to convert to java date.
  • how to compare with the current day.
  • and another way to compare with cron expressions: (10 18 16 Γ— * SUN, MON, WED, FRI *) and (0 30 9 30 *?)
  • Please explain the sample code using quartz or spring planning.
+6
source share
4 answers

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 using the Joda DateTime to compare the date.

+8
source

You might want to learn the org.quartz.CronExpression class in the Quartz API.

Note that you cannot simply compare a cron expression with a date, because a cron expression (usually) represents a sequence of different dates. In any case, you can find the following useful methods:

 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 is the following β€œtrigger” dates, i.e. Dates received from getNextValidTimeAfter ([some reference date]).

+4
source

I wrote a small class to handle cron expressions available here: https://github.com/frode-carlsen/cron

Based on Joda time, but it should be pretty easy to port api time to Java8. It also allows you to embed in unit tests, perform simulations, etc. by adjusting the DateTime offset in Joda-time.

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

Update Now the java 8 time api is supported, and also thanks to the contribution of the github user https://github.com/zemiak . In both cases, the expression parser is one tiny class that you can easily copy into your own project.

+4
source

Perhaps you can check cron-utils . It has some utilities to get the next / previous execution with a specific date, for example: now. Works with JodaTime, but you can get JavaDate from there. The library is an agnostic planner: you simply provide a string with a cron expression. Compatible with JDK6.

+3
source

Source: https://habr.com/ru/post/969773/


All Articles