Is there any java class to get Date from cron expression
Asked Answered
D

5

16

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 ?

Decrease answered 6/12, 2010 at 6:52 Comment(0)
D
21

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

Dessau answered 6/12, 2010 at 7:7 Comment(0)
T
23

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());
Twentyone answered 8/8, 2016 at 5:57 Comment(2)
Excellent answer! Simple, short and docs to boot. Perfect if using Spring as there's no need to add another third-party package. Thanks.Gaylegayleen
This is for default timezone. Use this new CronSequenceGenerator(cronExpression, your_timezone); for specific timezone.Angelicaangelico
D
21

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

Dessau answered 6/12, 2010 at 7:7 Comment(0)
R
9

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.

Regimen answered 10/9, 2015 at 16:47 Comment(0)
B
8

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);
Bina answered 4/4, 2014 at 15:13 Comment(0)
T
3

It looks like you could use either of these:

Tropine answered 6/12, 2010 at 7:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.