问题
I was wondering what is the most efficient way/best library to parse a cron expression and return a list of time points in Java.
For example I would have a cron expression, say, Fire every minute in October 2010
and would get a list/array of epoch times (or some other date format) returned that correspond to the times the trigger fires.
Thanks
回答1:
You could use org.quartz.CronExpression.getNextValidTimeAfter() . Using this method you can iteratively get as many trigger times as you wish.
You have to decide what will be the starting point of your iteration, will it be the current moment or epoch or smth else.
And you can parse a string cron expression into org.quartz.CronExpression
using constructor CronExpression(String cronExpression).
EDIT: you can find a similar functionality in the Spring framework's CronSequenceGenerator. Both could be used in the similar iterative fashion so you could check which one suits you the best regarding performance etc.
回答2:
cron-utils may be useful as an alternative to Quartz's CronExpression , since provides cron functionality without having to add a whole scheduler to the project. From the README, next execution can be calculated with the following snippet:
//Get date for next execution
DateTime now = DateTime.now();
CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(QUARTZ);
CronParser parser = new CronParser(cronDefinition);
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("* * * * * * *"));
DateTime nextExecution = executionTime.nextExecution(now));
In the same README, cron-utils is described as
A Java library to parse, validate, migrate crons as well as get human readable descriptions for them. The project follows the Semantic Versioning Convention and uses Apache 2.0 license.
来源:https://stackoverflow.com/questions/29318161/cron-expression-to-list-of-dates-timepoints