Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 495
Dima Avatar asked Sep 09 '14 06:09

Dima


People also ask

What is cron expression 0 * * * *?

Meaning of cron expression 0 * * * * *? I think it means the scheduler is expected to run every seconds.

Does quartz use cron?

Quartz uses the cron expression to store the firing schedule. The CronTrigger, which references the cron expression, is associated with the job at schedule time. Another difference between the UNIX cron expression format and Quartz is the number of supported fields in the expression.

What is Quartz cron expression?

A Cron Expressions quartz. Trigger. A cron expression is a string consisting of six or seven subexpressions (fields) that describe individual details of the schedule. These fields, separated by white space, can contain any of the allowed values with various combinations of the allowed characters for that field.


2 Answers

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);
}
like image 90
Markus Pscheidt Avatar answered Oct 17 '22 08:10

Markus Pscheidt


Will the CronTriggerFactoryBean.setCronExpression() method work?

like image 37
ivan.sim Avatar answered Oct 17 '22 08:10

ivan.sim