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();
}
}