package com.ed.cnc.servletListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.ed.cnc.city.StatisticsTask;
/** *//**
* 统计ContextListener
* @author westd
*
*/
/** *//**
* @author westd
*
*/
public class StatisticsContextListener implements ServletContextListener
{
private java.util.Timer timer = null;
/** *//**
* 这个方法在Web应用服务做好接受请求的时候被调用。
*
* @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent event)
{
timer = new java.util.Timer(true);
event.getServletContext().log("定时器已启动");
timer.schedule(new StatisticsTask(event.getServletContext()), 0, 60*60*1000);//每隔1小时
event.getServletContext().log("已经添加任务调度表");
}
/** *//**
* 这个方法在Web应用服务被移除,没有能力再接受请求的时候被调用。
*
* @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent event)
{
timer.cancel();
event.getServletContext().log("定时器销毁");
}
}
一个继承于TimerTask的一个类:StatisticsTask.java
package com.ed.cnc.city;
import java.util.Calendar;
import java.util.TimerTask;
import javax.servlet.ServletContext;
/** *//**
* 统计任务
* @author westd
*
*/
public class StatisticsTask extends TimerTask
{
private static final int STATISTICS_SCHEDULE_HOUR = 0;
private static boolean isRunning = false;
private ServletContext context = null;
public StatisticsTask(ServletContext context)
{
this.context = context;
}
@Override
public void run()
{
Calendar cal = Calendar.getInstance();
//System.out.println(isRunning);
if (!isRunning)
{
if (STATISTICS_SCHEDULE_HOUR == cal.get(Calendar.HOUR_OF_DAY)) //查看是否为凌晨
{
isRunning = true;
context.log("开始执行指定任务");
//TODO 添加自定义的详细任务
executeTask();
//指定任务执行结束
isRunning = false;
context.log("指定任务执行结束");
}
}
else
{
context.log("上一次任务执行还未结束");
}
}
/** *//**
* 执行任务
*/
public void executeTask()
{
System.out.println("任务1");
System.out.println("任务2");
}
}
web.xml中添加如下代码:
<listener>
<listener-class>com.ed.cnc.servletListener.StatisticsContextListener</listener-class>
</listener>