spring-bootscheduled-tasks

How to validate cron job with spring boot


I want to have a cron job that executes every 00:10 am

according to online validators this is the correct expression "0 0/10 0/00 ? * * *" but it has '?' and spring rejects this.

how can i validate my cron job properly ? my assumption is this should work '0 0/10 0/00 * * *' but it doesnt, please can someone point me in the right direction ? what am i doing wrong ? i will like to have a task 10 minutes after midnight

@Transactional
    @Scheduled(cron = "0 0/10 1/00 * * *")
    public void invalidateOutdatedPolicies() {
        InsurancePolicyStatus policyStatus =  
        System.out.println("Scheduled task done");
    }``

Solution

  • you can validate pattern like this

    public class ValidateCrontab {
        public static void main(String[] args) {
            // {second} {minute} {hour} {day} {month} {week} {year (optional)}
            // Second time, day, month and week, these 6 items are mandatory.
    
            CronSequenceGenerator cron1 = new CronSequenceGenerator("0 05 10 23 * ?");
            
            CronSequenceGenerator cron2 = new CronSequenceGenerator("0 05 08 ? * MON-FRI");
            Calendar cal = Calendar.getInstance();
    
            //cal.add(Calendar.DATE, 2); // add two days to current date
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
    
            System.out.println("current date " + sdf.format(cal.getTime()) +"\n ----");
    
            System.out.println("Next cron trigger date cron1 " + cron1.next(cal.getTime()));
            System.out.println("Next cron trigger date cron2 " + cron2.next(cal.getTime()));
        }
    }