Quartz Scheduler 更新任务触发器

有一些业务场景,我们需要手动去更新任务的触发时间,比如某个任务是每隔10分钟触发一次,现在需要改成每隔20分钟触发一次,这样既就需要手动的更新触发器

http://www.quartz-scheduler.org/documentation/quartz-2.1.x/cookbook/UpdateTrigger这里是官方的例子。

Replacing a trigger 替换触发器,通过triggerkey移除旧的触发器,同时添加一个新的进去。

// Define a new Trigger 
Trigger trigger = newTrigger()
    .withIdentity("newTrigger", "group1")
    .startNow()
    .build();

// tell the scheduler to remove the old trigger with the given key, and put the new one in its place
sched.rescheduleJob(triggerKey("oldTrigger", "group1"), trigger);

但是有一个地方需要注意:sched.rescheduleJob(triggerKey("oldTrigger", "group1"), trigger); 这个方法返回一个Date.

如果返回 null 说明替换失败,原因就是旧触发器没有找到,所以新的触发器也不会设置进去,下面是官方原文。

null if a Trigger with the given name & group was not found and removed from the store (and the new trigger is therefore not stored), otherwise the first fire time of the newly scheduled trigger is returned.

替换失败的原因一般有两种:一种情况是传入的triggerKey没有与之匹配的,另外一种情况就是旧触发器的触发时间已经全部完成,在触发完成后调度引擎会自动清除无用的触发器,这种情况也会匹配不到。

 

Updating an existing trigger 更新触发器,通过triggerkey获得触发器,重新配置。

// retrieve the trigger
Trigger oldTrigger = sched.getTrigger(triggerKey("oldTrigger", "group1");

// obtain a builder that would produce the trigger
TriggerBuilder tb = oldTrigger.getTriggerBuilder();

// update the schedule associated with the builder, and build the new trigger
// (other builder methods could be called, to change the trigger in any desired way)
Trigger newTrigger = tb.withSchedule(simpleSchedule()
    .withIntervalInSeconds(10)
    .withRepeatCount(10)
    .build();

sched.rescheduleJob(oldTrigger.getKey(), newTrigger);

 

 

posted @ 2013-05-30 21:47  大新博客  阅读(6763)  评论(0编辑  收藏  举报