Announcement Announcement Module
No announcement yet.
Dynamically Change the trigger for a scheduled task Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Dynamically Change the trigger for a scheduled task


    I have been playing around with Spring scheduling and created a simple scheduled task using the @Scheduled annotation and task:scheduler. This works very well and the annotations and task namespace simply everything. However I want to be able to dynamically change the trigger, I have checked a number of posts and could not find a satisfactory way of doing this. This is the solution that I have come up with.

    This is the application context:

    <utilroperties id="envProps" location=""/>

    <bean class="org.springframework.beans.factory.config.Pr opertyPlaceholderConfigurer">
    <property name="locations" value=""/>

    <context:component-scan base-package="com.colmac.test" />

    <task:scheduler id="scheduler"/>

    Here is the task that I want to run:

    public class MyTask implements Runnable{

    public void run() {
    System.out.println("MyTask runnable");

    And here is my scheduler:

    public class MyScheduler {

    ThreadPoolTaskScheduler tps;
    ScheduledFuture sf;

    CronTrigger trigger;

    public void setDelay(String cronExpression) {
    System.out.println("the trigger = " + cronExpression);
    trigger = new CronTrigger(cronExpression);

    MyTask task;

    public void start(){
    sf = tps.schedule(task, trigger);

    public void changeTrigger(String cronExpression){
    System.out.println("change trigger to: " + cronExpression);
    trigger = new CronTrigger(cronExpression);

    This seems to work for me. I am now able to start my schedular and dynamically change the trigger with a simple method call:

    myScheduler.changeTrigger("*/15 * * * * *");

    I am going to try next to see if I can use @Scheduled <task:annotation-driven scheduler="scheduler"/> and dynamically change the triggers in the annotated methods.

    If anyone has a simpler solution or can see any problems with this please let me know.