Cron Expression To List of Dates/Timepoints

和自甴很熟 提交于 2019-12-13 13:13:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!