Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Last Fired time using a Cron Expression in Java

Is there a way in Java to find the "Last Fired Time" from a Cron Expression?

E.g. If now = 25-Apr-2010 10PM, and the cron expression is 0 15 10 ? * * (quartz), it should return 25-Apr-2010 10:15AM.

Note:

  1. I do not care if we use standard cron expressions (like Unix and Quartz) or less popular ones if they can fetch me the correct "Last Fired Time"
  2. Also it is not literally "Last Fire time" as the trigger may not have fired, but logically there should be a way of telling when it (would have) fired last.
like image 985
a-sak Avatar asked Apr 26 '10 02:04

a-sak


2 Answers

cron-utils is an opensource Java library to parse, validate, migrate crons that supports the operation you need. To get the previous date from a cron before a given time simply:

//Get date for last execution
DateTime now = DateTime.now();
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("* * * * * * *"));
DateTime lastExecution = executionTime.lastExecution(now));

Bear in mind that in its current state it is a bit buggy and may not compute correctly for more complex cron expressions.

like image 84
João Neves Avatar answered Sep 19 '22 13:09

João Neves


First, I am not aware of an existing library that supports this. Quartz might, but the standard Java class libraries certainly don't.

Second, strictly speaking what you are asking for originally asked for is impossible. The best that a library can tell you is that the cron expression would have or should have fired. The only thing that could (theoretically) tell you the last time that a cron expression actually fired is the scheduler instance itself.

like image 22
Stephen C Avatar answered Sep 18 '22 13:09

Stephen C