Cron to human readable string [closed]
Asked Answered
B

5

19

I am using Quartz with Java to schedule jobs. One thing is that i store cron expressions on a database and i would like to present them to a user but in a more readable form. So i was wondering if there is a utility that could convert a cron expression into a human readable string. Something like :

""0 30 10-13 ? * WED,FRI" will become "Fires at 10:30, 11:30, 12:30, and 13:30, on every Wednesday and Friday."

Breazeale answered 5/8, 2009 at 20:23 Comment(2)
Did you ever implement a nice solution? I need to do exactly the same, do you have any hints/strategy that eases my implementation?Rowen
I'm afraid not... This was needed for production and my company did not see it as a priority. Instead we opted of simply displaying the next fire time for the cron jobs :S But the answer I accepted below provides a starting point to work with cron. I don't know how easy it would be though...Breazeale
L
33

A Java library that converts cron expressions into human readable strings: https://github.com/RedHogs/cron-parser

Lithomarge answered 6/3, 2014 at 21:1 Comment(2)
I love it that Stackoverflow provides the right answer to a question even 5 years after it was asked. :) CheersBreazeale
yes.. me too being help by this answer..Nagpur
A
9

Well yes I did understand your question. But I should have explained my answer a little better.

No I don’t know any tool that will help you get a cron expression in “human” readable form. But by getting access to the CronExpression you can create you own.

Try calling

cronTrigger.getExpressionSummary() 

on the cron expression:

"0/2 * * 4 * ?"

it returns the following String:

seconds: 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58
minutes: *
hours: *
daysOfMonth: 4
months: *
daysOfWeek: ?
lastdayOfWeek: false
nearestWeekday: false
NthDayOfWeek: 0
lastdayOfMonth: false
calendardayOfWeek: false
calendardayOfMonth: false
years: *

By having access to the CronExpression object, you can create your own "human" explenation.

Addicted answered 6/8, 2009 at 10:20 Comment(1)
yes thanks for the answer. it seems that i will create my version.Breazeale
C
5

cron-utils may be useful for this task, since provides human readable descriptions and does not require a fully fledged scheduler to provide them. Is well documented and supports multiple cron formats.

Below a code snippet from the docs:

//create a descriptor for a specific Locale
CronDescriptor descriptor = CronDescriptor.instance(Locale.UK);

//parse some expression and ask descriptor for description
String description = descriptor.describe(parser.parse("*/45 * * * * *"));
//description will be: "every 45 seconds"
Crossopterygian answered 20/10, 2015 at 9:49 Comment(0)
T
2

here's one i started. it uses the language that my users will ( probably ) understand.

it won't do that well with mixtures of tokens like '1,13,16-23,L' for the dayofmonth token, but hopefully, i'll have some time to spend on it before my users become that sophisticated:

package com.tacteonltd.control.cron;

import java.util.StringTokenizer;

import com.tacteonltd.control.string.STRING;
import com.tacteonltd.control.time.TIME;

public class CRON {
    public static String humanReadable(String value){
        StringBuffer sb = new StringBuffer();
        try{
            StringTokenizer tokens = new StringTokenizer(value, " ", false);
            humanizeSeconds(tokens.nextToken(), sb);sb.append("\n");
            humanizeMinutes(tokens.nextToken(), sb);sb.append("\n");
            humanizeHours(tokens.nextToken(), sb);sb.append("\n");
            String dom = tokens.nextToken();
            String month = tokens.nextToken();
            String dow = tokens.nextToken();
            humanizeDOMs(dom, dow, sb);sb.append("\n");
            humanizeMonths(month, sb);sb.append("\n");
            humanizeDOWs(dow, dom, sb);
        }catch(Throwable t){
            t.printStackTrace();
        }
        return sb.toString();
    }
    private static void humanizeDOWs(String value, String dom, StringBuffer sb){
        value=value.trim();
        if(STRING.isNumeric(value)){
            sb.append("and the " + value + postFix(value) + " day-of-the-week("+TIME.getWeekDayName(Integer.parseInt(value))+"). "); 
        }
        else if(value.equals("*"))
        {
            sb.append("and every day-of-the-week. ");
        }
        else if(value.equals("?"))
        {
            sb.append("and whatever day-of-the-week it is for day"+(STRING.isNumeric(dom) ? "":"s")+"-of-the-month :"+(STRING.isNumeric(dom) ? dom:"that match"+(STRING.isNumeric(dom) ? "es":"")+" " + dom + "."));
        }
        else if(value.indexOf("/")>-1){
            String first = value.substring(0, value.indexOf("/"));
            String every = value.substring(value.indexOf("/") + 1);
            sb.append("and the " + first + postFix(first) + " day-of-the-week and every " + every + " day" + (Integer.parseInt(every) == 1 ? "":"s") + " following. "); 
        }
        else if(value.indexOf(",")>-1){
            StringTokenizer tokens = new StringTokenizer(value, ",", false);
            sb.append("and the following days of the week: ");
            int added = 0;
            while(tokens.hasMoreTokens()){
                String token = tokens.nextToken();
                sb.append((added==0 ? "":", ") + token);added++;
            }
            sb.append(".");
        }
        else if(value.indexOf("-")>-1){
            StringTokenizer tokens = new StringTokenizer(value, "-", false);
            sb.append("and for every day of the week from " + tokens.nextToken() + " through " + tokens.nextToken() + ". ");
        }
        else {
            sb.append("and the following days of the week: " + value + ".");
        }
    }
    private static void humanizeMonths(String value, StringBuffer sb){
        value=value.trim();
        if(STRING.isNumeric(value)){
            sb.append("the " + value + postFix(value) + " month("+TIME.getMonthName(Integer.parseInt(value))+"), "); 
        }
        else if(value.equals("*"))
        {
            sb.append("every month, ");
        }
        else if(value.indexOf("/")>-1){
            String first = value.substring(0, value.indexOf("/"));
            String every = value.substring(value.indexOf("/") + 1);
            sb.append("the " + first + postFix(first) + " month("+TIME.getMonthName(Integer.parseInt(value))+") and every " + every + " month" + (Integer.parseInt(every) == 1 ? "":"s") + " following, "); 
        }
        else if(value.indexOf(",")>-1){
            StringTokenizer tokens = new StringTokenizer(value, ",", false);
            sb.append("the following months: ");
            int added = 0;
            while(tokens.hasMoreTokens()){
                sb.append((added==0 ? "":", ") + tokens.nextToken());added++;
            }
        }
    }
    private static void humanizeDOMs(String value, String dow, StringBuffer sb){
        value=value.trim();
        if(STRING.isNumeric(value)){
            sb.append("the " + value + postFix(value) + " day-of-the-month, "); 
        }
        else if(value.equals("*"))
        {
            sb.append("every day-of-the-month, ");
        }
        else if(value.equals("?"))
        {
            sb.append("whatever day-of-the-month falls upon " + dow + " , ");
        }
        else if(value.indexOf("-")>-1){
            StringTokenizer tokens = new StringTokenizer(value, "-", false);
            String from = tokens.nextToken();
            String through = tokens.nextToken();
            int year = TIME.getYear(System.currentTimeMillis());
            int month = TIME.getMonth(System.currentTimeMillis());
            String last_dom = "" + TIME.getLastDOM(year, month);
            sb.append("for every day of the month from " + from + " through " + (through.equals("L") ? "the last("+year +"." +month + "."+last_dom+")":through) );
        }
        else if(value.indexOf("/")>-1){
            String first = value.substring(0, value.indexOf("/"));
            String every = value.substring(value.indexOf("/") + 1);
            sb.append("the " + first + postFix(first) + " day-of-the-month and every " + every + " day" + (Integer.parseInt(every) == 1 ? "":"s") + " following, "); 
        }
        else if(value.indexOf(",")>-1){
            StringTokenizer tokens = new StringTokenizer(value, ",", false);
            sb.append("the following days of the month: ");
            int added = 0;
            while(tokens.hasMoreTokens()){
                String token = tokens.nextToken();
                if(token.equals("L")){
                    int year = TIME.getYear(System.currentTimeMillis());
                    int month = TIME.getMonth(System.currentTimeMillis());
                    String last_dom = "" + TIME.getLastDOM(year, month);
                    sb.append((added==0 ? "":", ") + "the last("+year +"." +month + "."+last_dom+")");
                }
                else{
                    sb.append((added==0 ? "":", ") + token);added++;
                }
            }
        }
    }
    private static void humanizeSeconds(String value, StringBuffer sb){
        value=value.trim();
        if(STRING.isNumeric(value)){
            sb.append("on the " + value + postFix(value) + " second, "); 
        }
        else if(value.equals("*"))
        {
            sb.append("on every second, ");
        }
        else if(value.indexOf("/")>-1){
            String first = value.substring(0, value.indexOf("/"));
            String every = value.substring(value.indexOf("/") + 1);
            sb.append("on the " + first + postFix(first) + " second and every " + every + " second" + (Integer.parseInt(every) == 1 ? "":"s") + " following, "); 
        }
        else if(value.indexOf("-")>-1){
            StringTokenizer tokens = new StringTokenizer(value, "-", false);
            sb.append("for every second from " + tokens.nextToken() + " through " + tokens.nextToken() + " ");
        }
        else if(value.indexOf(",")>-1){
            StringTokenizer tokens = new StringTokenizer(value, ",", false);
            sb.append("on the following seconds: ");
            int added = 0;
            while(tokens.hasMoreTokens()){
                sb.append((added==0 ? "":", ") + tokens.nextToken());added++;
            }
        }
    }
    private static void humanizeMinutes(String value, StringBuffer sb){
        value=value.trim();
        if(STRING.isNumeric(value)){
            sb.append("the " + value + postFix(value) + " minute, "); 
        }
        else if(value.equals("*"))
        {
            sb.append("every minute, ");
        }
        else if(value.indexOf("/")>-1){
            String first = value.substring(0, value.indexOf("/"));
            String every = value.substring(value.indexOf("/") + 1);
            sb.append("the " + first + postFix(first) + " minute and every " + every + " minute" + (Integer.parseInt(every) == 1 ? "":"s") + " following, "); 
        }
        else if(value.indexOf("-")>-1){
            StringTokenizer tokens = new StringTokenizer(value, "-", false);
            sb.append("for every minute from " + tokens.nextToken() + " through " + tokens.nextToken() + " ");
        }
        else if(value.indexOf(",")>-1){
            StringTokenizer tokens = new StringTokenizer(value, ",", false);
            sb.append("the following minutes: ");
            int added = 0;
            while(tokens.hasMoreTokens()){
                sb.append((added==0 ? "":", ") + tokens.nextToken());added++;
            }
        }
    }
    private static void humanizeHours(String value, StringBuffer sb){
        value=value.trim();
        if(STRING.isNumeric(value)){
            sb.append("the " + value + postFix(value) + " hour, "); 
        }
        else if(value.equals("*"))
        {
            sb.append("every hour, ");
        }
        else if(value.indexOf("/")>-1){
            String first = value.substring(0, value.indexOf("/"));
            String every = value.substring(value.indexOf("/") + 1);
            sb.append("the " + first + postFix(first) + " hour and every " + every + " hour" + (Integer.parseInt(every) == 1 ? "":"s") + " following, "); 
        }
        else if(value.indexOf("-")>-1){
            StringTokenizer tokens = new StringTokenizer(value, "-", false);
            sb.append("for every hour from " + tokens.nextToken() + " through " + tokens.nextToken() + " ");
        }
        else if(value.indexOf(",")>-1){
            StringTokenizer tokens = new StringTokenizer(value, ",", false);
            sb.append("the following hours: ");
            int added = 0;
            while(tokens.hasMoreTokens()){
                sb.append((added==0 ? "":", ") + tokens.nextToken());added++;
            }
        }
    }
    private static String postFix(String value){
        String post = null; 
            if(value.substring(value.length()-1).equals("1"))post = "st";
            else if(value.substring(value.length()-1).equals("2"))post = "nd";
            else if(value.substring(value.length()-1).equals("3"))post = "rd";
            else post="th";
        return post;
    }
}
Trackless answered 19/9, 2010 at 1:19 Comment(0)
A
-2

The CronTrigger creates a CronExpression object from the cron expression String. But you cannot get access to it. But by using reflection you can:

Class c = cronTrigger.getClass();
Field f = c.getDeclaredField("cronEx");
f.setAccessible(true);
CronExpression cronEx = (CronExpression) f.get(cronTrigger);
Addicted answered 5/8, 2009 at 22:25 Comment(1)
i think you didn't understand my questionBreazeale

© 2022 - 2024 — McMap. All rights reserved.