public class TaskManager implements ServletContextListener{
private java.util.Timer timer = null;
public void contextInitialized(ServletContextEvent event) {
timer = new java.util.Timer(true);
event.getServletContext().log("定时器已启动");
timer.schedule(new MyTask(event.getServletContext()), 0, 60*60*1000); //每一个小时看一次
event.getServletContext().log("已经添加任务调度表");
}
public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
event.getServletContext().log("定时器销毁");
}
}
class MyTask extends TimeTask {
private static final int C_SCHEDULE_HOUR = 0; //晚上0点时,执行
private static boolean isRunning = false;
private ServletContext context = null;
public MyTask(ServletContext context) {
this.context = context;
}
public void run() {
Calendar cal = Calendar.getInstance();
if (!isRunning) {
if (C_SCHEDULE_HOUR == cal.get(Calendar.HOUR_OF_DAY)) {
isRunning = true;
context.log("开始执行指定任务");
//TODO 添加自定义的详细任务,以下只是示例
int i = 0;
while (i++ < 10) {
context.log("已完成任务的" + i + "/" + 10);
}
timerDoSomething();
isRunning = false;
context.log("指定任务执行结束");
}
} else {
context.log("上一次任务执行还未结束");
}
}
public static timerDoSomething(){
System.out.println("我已经执行了一次了!!!!!");
}
}