监听器结合java定时器做的一个任务调度,为什么不执行?
需求:
需要在每天特定的时候启动一个程序进行处理特定任务,比如说数据库清理,公司财务报表上传等。这些任务启动会处理很久,所以希望在某个特定时间段,系统压力比较小的时候做处理,比如说晚上12点。
问题:
现在我写了个监听器,特定时间选在下午15点,为什么启动后,在15点,程序没反应?
1.监听器类:
package com.test;
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* Application Lifecycle Listener implementation class ContextListener
*
*/
public class ContextListener implements ServletContextListener {
private Timer timer = null;
/**
* Default constructor.
*/
public ContextListener() {
// TODO Auto-generated constructor stub
}
/**
* @see ServletContextListener#contextDestroyed(ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
event.getServletContext().log("定时器销毁");
}
/**
* @see ServletContextListener#contextInitialized(ServletContextEvent)
*/
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("已经添加任务调度表");
}
}
2.Task
package com.test;
import java.util.Calendar;
import java.util.TimerTask;
import javax.servlet.ServletContext;
public class MyTask extends TimerTask {
private static final int C_SCHEDULE_HOUR = 15;
private static boolean isRunning = false;
private ServletContext context = null;
public MyTask(ServletContext context) {
this.context = context;
}
@Override
public void run() {
Calendar cal = Calendar.getInstance();
if (!isRunning) {
if (C_SCHEDULE_HOUR == cal.get(Calendar.HOUR_OF_DAY)) {
isRunning = true;
context.log("开始执行指定任务");
System.out.println("开始执行指定任务");
int i = 0;
while (i++ < 10) {
context.log("已完成任务的" + i + "/" + 10);
System.out.println("已完成任务的" + i + "/" + 10);
}
isRunning = false;
context.log("指定任务执行结束");
System.out.println("指定任务执行结束");
}
} else {
context.log("上一次任务执行还未结束");
}
}
}
3.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>
TestTimer </display-name>
<listener>
<listener-class>com.test.ContextListener </listener-class>
</listener> <welcome-file-list>
<welcome-file>index.html </welcome-file>
<welcome-file>index.htm </welcome-file>
<welcome-file>index.jsp </welcome-file>
<welcome-file>default.html </welcome-file>
<welcome-file>default.htm </welcome-file>