javaquartz-schedulercronexpression

Quartz CronTrigger executing jobs on wrong date/time


I am using following cron expression to execute a job on every Friday at specified time of day (in sample below it's 1:13 PM).

0 13 13 ? * FRI

So expected behaviour should be if I initialize this trigger any day other then Friday then it should not start executing until next Friday. But whats happening in my case is even if I initialized this trigger today (as today is Wednesday), it starts executing jobs at the very moment.

Relevant java source:

CronTrigger cronTrigger = new CronTrigger("trigger_" + groupName, groupName, cronExpression);
cronTrigger.setStartTime(startDate); //startDate = 1-Mar-2012
cronTrigger.setEndTime(endDate);     //endDate   = 30-Apr-2012

Solution

  • Your issue is configuring the startTime. startTime is meant to be the time at at which the trigger should occur. Since the date is old this causes a misfire in the scheduler and the default behavior is for the scheduler to immediately refire.

    Remove setStartTime, the default behavior is for startTime to be set to the current time and the first trigger time will be the match to the cron trigger after the start time so this Thursday.

    Quick little test I through together to verify:

    public class Test {
        public static void main(String[] args) throws ParseException, SchedulerException {
            String groupName = "group";
            String cronExpression = "0 13 13 ? * THUR";
    
            CronTrigger cronTrigger = new CronTrigger("trigger_" + groupName, groupName, cronExpression);
            cronTrigger.setStartTime(new Date(0));
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            JobDetail detail = new JobDetail("testJob", groupName, TestJob.class);
            scheduler.scheduleJob(detail, cronTrigger);
            scheduler.start();
            try {
                Thread.sleep(50001);
            } catch (Exception ignore) {
            }
    
        }
    
        public static class TestJob implements Job {
            public void execute(JobExecutionContext context) throws JobExecutionException {
                System.out.println("TEST");
            }
        }
    }
    

    When removing the setStartTime my print message does not trigger. With it there the print message triggers.