How to convert CRON string to ScheduleExpression in Java?

后端 未结 1 1406
清歌不尽
清歌不尽 2021-01-21 23:36

I got this problem:

I have a text field,

There should be a CRON expression written, and later on saved.

Now I need a method to convert the CRON string (

相关标签:
1条回答
  • 2021-01-21 23:58

    I found the answer, but forgot to answer it, here is the code that worked for me:

    private ScheduleExpression parseCronExpressionToScheduleExpression(String cronExpression) {
    
        if ("never".equals(cronExpression)) {
            return null;
        }
    
        // parsing it more or less like cron does, at least supporting same fields (+ seconds)
    
        final String[] parts = cronExpression.split(" ");
        final ScheduleExpression scheduleExpression;
    
        if (parts.length != 6 && parts.length != 5) {
            scheduleExpression = scheduleAliases.get(cronExpression);
            if (scheduleExpression == null) {
                throw new IllegalArgumentException(cronExpression + " doesn't have 5 or 6 segments as excepted");
            }
            return scheduleExpression;
        } else if (parts.length == 6) { // enriched cron with seconds
            return new ScheduleExpression()
                    .second(parts[0])
                    .minute(parts[1])
                    .hour(parts[2])
                    .dayOfMonth(parts[3])
                    .month(parts[4])
                    .dayOfWeek(parts[5]);
        }
    
        // cron
        return new ScheduleExpression()
                .minute(parts[0])
                .hour(parts[1])
                .dayOfMonth(parts[2])
                .month(parts[3])
                .dayOfWeek(parts[4]);
    }
    

    So, if you send the cron expression to the function, it will make a shedule expression out of it, but it does not work 100% on all cron expressions but on most

    Here is what worked for the individual positions in the cron expression

    *    works 
    -    works
    ,    works
    /    works
    last works (only in the part Day Of Month)
    

    What does not work are the letters, such as L, and the others, at least not when I last checked.

    Hope this will help the next guy :)

    0 讨论(0)
提交回复
热议问题