有一些業務場景,我們需要手動去更新任務的觸發時間,比如某個任務是每隔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);