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

  • Dynamically Change the trigger for a scheduled task

    Hi,

    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="env.properties"/>

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

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

    <task:scheduler id="scheduler"/>

    Here is the task that I want to run:

    @Service
    public class MyTask implements Runnable{


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

    And here is my scheduler:

    @Service
    public class MyScheduler {

    @Autowired
    ThreadPoolTaskScheduler tps;
    ScheduledFuture sf;

    CronTrigger trigger;


    @Value("#{envProps.delay}")
    public void setDelay(String cronExpression) {
    System.out.println("the trigger = " + cronExpression);
    trigger = new CronTrigger(cronExpression);
    }

    @Autowired
    MyTask task;

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

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

    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.

    Thanks

    Jim
Working...
X