spring定時器按照指定時間進行執行
阿新 • • 發佈:2018-12-30
一般我們使用spring定時器的時候都是配置的固定時間在spring配置檔案中,如果我們有一個時間設定頁面,通過這個頁面設定定時器的執行時間,就可以達到動態執行的效果。
上程式碼:
package com.test.action; import java.text.ParseException; import javax.annotation.Resource; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.springframework.scheduling.quartz.CronTriggerBean; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.opensymphony.xwork2.ActionSupport; public class TestAction extends ActionSupport{ @Resource public CronTriggerBean triggerBean; //系統 public CronTriggerBean triggerTempBean; @Resource private Scheduler scheduler; private String configTime; public String configTime(){ try { /*得到系統設定的定時器執行時間*/ System.out.println(triggerBean.getCronExpression()); /*得到指定定時器, testDoTrigger為applicationContext.xml中CronTriggerBean*/ triggerTempBean = (CronTriggerBean) scheduler.getTrigger("testDoTrigger", Scheduler.DEFAULT_GROUP); /*指定定時器的執行時間*/ System.out.println(triggerTempBean.getCronExpression()); /*將指定定時器的執行時間設定為從前臺傳遞過來的時間*/ triggerTempBean.setCronExpression(configTime); /*讓設定生效*/ scheduler.rescheduleJob("testDoTrigger", Scheduler.DEFAULT_GROUP,triggerTempBean); } catch(ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch(SchedulerException e) { // TODO Auto-generated catch block e.printStackTrace(); } return SUCCESS; } public String getConfigTime(){ return configTime; } public void setConfigTime(String configTime){ this.configTime = configTime; } }