Parsing CRON expression in Java

Posted on 08-01-2013 11:02 by graham
This tutorial shows you how to parse a CRON expression from string into a more friendly form.

Parsing a CRON expression


We will use the org.quartz.CronExpression class. Having a cron expression in string form, we can pass it to the CronExpression constructor:
CronExpression expr = new CronExpression("0 */5 * * * ?");

As a result we will have an object of type CronExpression on which we can check some properties of the CRON expression.

Getting next matching time


To check the next valid point in time that matches the given expression we use the method getNextValidTimeAfter:
// check the next fire time
System.out.println("The nearest fire time is " + expr.getNextValidTimeAfter(new Date()));

Possible issues


When parsing a CRON expression like above, you might encounter the following exception:
Caused by: java.lang.UnsupportedOperationException: support for specifying both a day-of-week and a day-of-month parameter is not implemented

This means that only one of the following values: day-of-week or day-of-month can be specified. In a cron expression like the following:
0 */5 * * * *

day of month is the fourth field, and day of week - the sixth one. One of them has to have value ?. To fix the exception above, we will replace the asterisk representing the day of week with a question mark:
0 */5 * * * ?
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems