Priya Priya - 6 months ago 51
Java Question

Is there any Java code for creating Cron Expression?

I need a Java code to create a cron expression based on user inputs.
User inputs are Time, frequency and number of executions.

Answer

Just adding on from the comment that says create it yourself.

Here is an example: Prompt the user for the values and pass them into the following method, the Javadoc explains what is allowed in which value (taken from http://en.wikipedia.org/wiki/Cron#Format).

This is untested and doesn't validate any of the input strings, but I'm sure you can do that.

/**
 * Generate a CRON expression is a string comprising 5 or 6 fields separated by white space.
 * @param minutes mandatory = yes. allowed values = {@code  0-59    * / , -}
 * @param hours mandatory = yes. allowed values = {@code 0-23   * / , -}
 * @param dayOfMonth mandatory = yes. allowed values = {@code 1-31  * / , - ? L W}
 * @param month mandatory = yes. allowed values = {@code 1-12 or JAN-DEC    * / , -}
 * @param dayOfWeek mandatory = yes. allowed values = {@code 0-6 or SUN-SAT * / , - ? L #}
 * @param year mandatory = no. allowed values = {@code 1970–2099    * / , -}
 * @return a CRON Formatted String.
 */
private String generateCronExpression(final String minutes, final String hours, final String dayOfMonth, final String month, final String dayOfWeek, final String year) {
    return String.format("%1$s %2$s %3$s %4$s %5$s %6%s", minutes, hours, dayOfMonth, month, dayOfWeek, year);
}

Cron Format Information taken from here: http://en.wikipedia.org/wiki/Cron#Format

Comments