基本思路如下:
1、定义一个实现了ServletContextListener的类
2、在contextInitialized()和contextDestroyed()调用自定义的定时程序
3、在web.xml里面配置这个 ServletContextListener
代码示例:
(程序来源 http://blog.csdn.net/zhuche110/archive/2008/05/06/2400122.aspx)
public class WorkServiceImpl implements WorkService , ServletContextListener{
public void contextDestroyed(ServletContextEvent arg0){
timer.cancel();
System.out.println("定时器已销毁");
}
public void contextInitialized(ServletContextEvent event){
timer = new java.util.Timer(true);
sampleTask = new SampleTask(event.getServletContext());
System.out.println("定时器已启动");
timer.schedule(sampleTask, 0, 60 * 60 * 1000);
System.out.println("已经添加任务调度表");
}
}
class SampleTask extends TimerTask{
private ServletContext context;
private static boolean isRunning = false;
private static boolean flag = true;
private static final int C_SCHEDULE_HOUR = 23;
private WorkServiceImpl workService;
public SampleTask(ServletContext context){
this.context = context;
}
public void run() {
workService = new WorkServiceImpl();
Calendar cal = Calendar.getInstance();
if (!isRunning){
if (C_SCHEDULE_HOUR == cal.get(Calendar.HOUR_OF_DAY) && flag){
isRunning = true;
workService.autoWorkOff();
isRunning = false;
flag = false;
context.log("指定任务执行结束");
}
} else{
context.log("上一次任务执行还未结束");
}
if(C_SCHEDULE_HOUR != cal.get(Calendar.HOUR_OF_DAY)){
flag = true;
}
}
}
要使用此监听器需要在web.xml中配置,如下:
<listener>
<listener-class>com.css.wam.service.impl.WorkServiceImpl </listener-class>
</listener>
1、定义一个实现了ServletContextListener的类
2、在contextInitialized()和contextDestroyed()调用自定义的定时程序
3、在web.xml里面配置这个 ServletContextListener
代码示例:
(程序来源 http://blog.csdn.net/zhuche110/archive/2008/05/06/2400122.aspx)
public class WorkServiceImpl implements WorkService , ServletContextListener{
public void contextDestroyed(ServletContextEvent arg0){
timer.cancel();
System.out.println("定时器已销毁");
}
public void contextInitialized(ServletContextEvent event){
timer = new java.util.Timer(true);
sampleTask = new SampleTask(event.getServletContext());
System.out.println("定时器已启动");
timer.schedule(sampleTask, 0, 60 * 60 * 1000);
System.out.println("已经添加任务调度表");
}
}
class SampleTask extends TimerTask{
private ServletContext context;
private static boolean isRunning = false;
private static boolean flag = true;
private static final int C_SCHEDULE_HOUR = 23;
private WorkServiceImpl workService;
public SampleTask(ServletContext context){
this.context = context;
}
public void run() {
workService = new WorkServiceImpl();
Calendar cal = Calendar.getInstance();
if (!isRunning){
if (C_SCHEDULE_HOUR == cal.get(Calendar.HOUR_OF_DAY) && flag){
isRunning = true;
workService.autoWorkOff();
isRunning = false;
flag = false;
context.log("指定任务执行结束");
}
} else{
context.log("上一次任务执行还未结束");
}
if(C_SCHEDULE_HOUR != cal.get(Calendar.HOUR_OF_DAY)){
flag = true;
}
}
}
要使用此监听器需要在web.xml中配置,如下:
<listener>
<listener-class>com.css.wam.service.impl.WorkServiceImpl </listener-class>
</listener>