How to change cron expression in CronTrigger (quartz 2.2, spring 4.1)

14,232

Solution 1

Will the CronTriggerFactoryBean.setCronExpression() method work?

Solution 2

In addition to the CronTriggerFactoryBean you probably have a SchedulerFactoryBean, which provides access to the Quartz scheduler as well as the CronTrigger. The Quartz scheduler allows you to reschedule a job with a new/modified trigger:

@Autowired private SchedulerFactoryBean schedulerFactoryBean;
...
public void rescheduleCronJob() {

    String newCronExpression = "..."; // the desired cron expression

    Scheduler scheduler = schedulerFactoryBean.getScheduler();
    TriggerKey triggerKey = new TriggerKey("timeSyncTrigger");
    CronTriggerImpl trigger = (CronTriggerImpl) scheduler.getTrigger(triggerKey);
    trigger.setCronExpression(newCronExpression );
    scheduler.rescheduleJob(triggerKey, trigger);
}
Share:
14,232
Dima
Author by

Dima

Updated on June 09, 2022

Comments

  • Dima
    Dima almost 2 years

    I'm a bit stuck migrating to latest quartz 2.2 and spring 4.1... Here's a cron trigger, I omit the job and other fluff for clarity:

    ...
           <bean id="timeSyncTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
             <property name="jobDetail" ref="timeSyncJob"/>
             <property name="startDelay" value="10000"/>
             <property name="cronExpression" value="0 0 1 * * ? *"/>
           </bean>
    ...
    

    Now, I need to change its cronExpression at run time, and it's not as simple as I thought. I can't reference the bean and change the property because its a factory giving CronTrigger interface which in turn doesn't have setCronExpression method any longer, it has become immutable. Before I could simply fish out a trigger from the context and set its new cron expression. It worked very well for many years, until the upgrade become unavoidable.

    So, how do we accomplish this simple task today? Totally lost in documentations and versions.. Thanks in advance!