是否有任何 java 类可以从 cron 表达式中获取日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4363952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:02:44  来源:igfitidea点击:

Is there any java class to get Date from cron expression

javadatecroncronexpression

提问by Unicorn

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 ?

我需要找出给定 cron 表达式表示的日期和时间的第一次出现。是否有任何 Java 类、实用程序代码可以帮助从给定的 cron 表达式中获取数据对象?

回答by saugata

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

您可以检查org.quartz.CronExpression它有一个名为 getNextValidTimeAfter 的方法,您可以使用它。

回答by villager

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

您还可以利用 spring 的http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html为此

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

回答by nMoncho

If you're using Spring you could use:

如果您使用的是 Spring,则可以使用:

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

回答by Jo?o Neves

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

这是类似于 Quartz 的 CronExpression 的替代方案,但无需向您的项目添加成熟的调度程序: 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-utilsis:

根据官方的描述,cron-utils是:

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.

一个用于解析、验证、迁移 cron 以及为它们获取人类可读描述的 Java 库。该项目遵循语义版本控制约定并使用 Apache 2.0 许可证。

回答by javamonkey79

It looks like you could use either of these:

看起来您可以使用以下任一方法: