配置監聽器,建立執行緒定時執行業務邏輯

passport_daizi發表於2012-06-08

1:配置監聽器:


在web.xml中配置監聽器:

<web-app>

...

<listener>
<listener-class>com.
xiami.listener.MyLister</listener-class>
</listener>

</web-app>


2:新建監聽器類MyLister


public class MyLister implements ServletContextListener {

private Timer timer = null;


public void contextDestroyed(ServletContextEvent sce) {
timer.cancel();
}

public void contextInitialized(ServletContextEvent sce) {

//建立一個新計時器,指定其相關的執行緒作為守護程式執行
timer = new Timer(true);
try{

//既時執行MyThread任務,86400000毫秒後重復執行。 
timer.schedule(new MyThread(), 0, 86400000);
}catch(Exception e){
e.printStackTrace();
}
}
}


3:建立MyThread任務類(執行緒)

public class MyThread extends TimerTask  implements Runnable {

public boolean bl = false;
private Thread t;
public MyThread(){

}
public MyThread(String _year, String _month, String _date){
year = _year;
month = _month;
date = _date;
}

/**
 * 停止執行緒
 */
public void stop(Thread t){
this.t = t;
System.out.println("程式被終止*****************");
}

public void run(){
boolean flag = true;
while(flag){

//處理一些業務邏輯、
flag = new PersonBaseDataQuery().getRkxzl();
}


}

相關文章