Is there any java class to get Date from cron expression

白昼怎懂夜的黑 提交于 2019-12-19 05:33:31

问题


I need to find out the first occurrence of Date and time represented by given cron expression. Is there any java class, utility code which can help in getting data object from given cron expression ?


回答1:


You can check org.quartz.CronExpression It has a method named getNextValidTimeAfter which you can use.




回答2:


You can also leverage on spring's http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html for this

CronSequenceGenerator generator = new CronSequenceGenerator(cronExpression);
Date nextRunDate= generator.next(new Date());



回答3:


If you're using Spring you could use:

CronTrigger trigger = new CronTrigger(cron);
TriggerContext context = new TriggerContext() {

public Date lastScheduledExecutionTime() {
    return null;
}

public Date lastActualExecutionTime() {
    return null;
}

public Date lastCompletionTime() {
    return null;
}
};
return trigger.nextExecutionTime(context);



回答4:


Here's an alternative similar to Quartz's CronExpression but without having to add a fully fledged scheduler to your project: cron-utils

You can get the date you need with the following:

//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));

According to the official description, cron-utils is:

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.




回答5:


It looks like you could use either of these:

  • j-cron-expression
  • Quartz CronTrigger class


来源:https://stackoverflow.com/questions/4363952/is-there-any-java-class-to-get-date-from-cron-expression

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