在項目中使用到定時任務,出來使用Spring自帶的調度之外,還可以使用Servlet上下文實現
一、創建一個Listener 類,實現ServletContextListener 介面,實現介面中的方法:
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* 偵聽器類 和Timer 結合起來定時執行任務
*/
public class ContextListener implements ServletContextListener {
private java.util.Timer timer = null;
public void contextInitialized(ServletContextEvent arg0) {
timer = new java.util.Timer(true);// 創建一個新計時器,指定其相關的線程作為守護程序運行.
//System.out.println("啟動定時器");
//調度器,EarlyWarningTask() 為自定義調度任務
//初始化時就執行一次任務
timer.schedule(new EarlyWarningTask(),10, 60*60*1000);//執行任務前延遲10毫秒,執行任務的間隔60*60*1000毫秒
//System.out.println("調度任務添加完成");
}
public void contextDestroyed(ServletContextEvent arg0) {
timer.cancel();
//System.out.println("定時任務銷毀");
}
}
二、獲得Spring 的ApplicationContext配置信息,以便在調度任務中讀取配置文件中的相關業務方法
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppContext {
private static AppContext instance;
private AbstractApplicationContext appContext;
public synchronized static AppContext getInstance() {
if (instance == null) {
instance = new AppContext();
}
return instance;
}
private AppContext() {
this.appContext = new ClassPathXmlApplicationContext(
"/applicationContext.xml");
}
public AbstractApplicationContext getAppContext() {
return appContext;
}
}
三、自定義調度任務類,繼承TimerTask 類
import java.util.TimerTask;
public class EarlyWarningTask extends TimerTask {
private static final int C_SCHEDULE_HOUR = 23;//執行時間23時
private static boolean isRunning = false;
//通過AppContext 類,獲得配置文件中相關業務方法
//inStorageDetailImp
protected IInStorageDetailService getInStorageDetailService(){
return (IInStorageDetailService)AppContext.getInstance().getAppContext()
.getBean("inStorageDetailImp");
}
// goodsWarningImp
protected IGoodsWarningService getGoodsWarningService(){
return (IGoodsWarningService)AppContext.getInstance().getAppContext()
.getBean("goodsWarningImp");
}
// lendOutAccountImp
protected ILendOutAccountService getLendOutAccountService(){
return (ILendOutAccountService) AppContext.getInstance().getAppContext()
.getBean("lendOutAccountImp");
}
//lendOutWarningImp
protected ILendOutWarningService getLendOutWarningService(){
return (ILendOutWarningService)AppContext.getInstance().getAppContext()
.getBean("lendOutWarningImp");
}
//任務在run()方法中實現
@Override
public void run() {
Calendar cal = Calendar.getInstance() ;
if(!isRunning){
if(C_SCHEDULE_HOUR==cal.get(Calendar.HOUR_OF_DAY)){//HOUR_OF_DAY 用於 24 小時制時鐘
isRunning = true;
System.out.println("執行定時任務");
//任務代碼
//…………………………
isRunning = false;
System.out.println("定時任務結束");
}else {
System.out.println("未到定時任務時間");
}
}else{
System.out.println("上一個定時任務未結束");
}
}
四、web.xml配置監聽
<listener>
<listener-class>com.cl.gdb.util.ContextListener</listener-class>
</listener>
[火星人 ] 使用Servlet上下文實現偵聽器已經有318次圍觀