packagecom.ed.cnc.servletListener;
imp<wbr>ortjavax.servlet.ServletContextEvent;</wbr>
imp<wbr>ortjavax.servlet.ServletContextListener;</wbr>
imp<wbr>ortcom.ed.cnc.city.StatisticsTask;</wbr>
/***//**
*统计ContextListener
*@authorwestd
*
*/
/***//**
*@authorwestd
*
*/
publicclassStatisticsContextListenerimplementsServletContextListener
{
privatejava.util.Timertimer=null;
/***//**
*这个方法在Web应用服务做好接受请求的时候被调用。
*
*@seejavax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
*/
publicvoidcontextInitialized(ServletContextEventevent)
{
timer=newjava.util.Timer(true);
event.getServletContext().log("定时器已启动");
timer.schedule(newStatisticsTask(event.getServletContext()),0,60*60*1000);//每隔1小时
event.getServletContext().log("已经添加任务调度表");
}
/***//**
*这个方法在Web应用服务被移除,没有能力再接受请求的时候被调用。
*
*@seejavax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
*/
publicvoidcontextDestroyed(ServletContextEventevent)
{
timer.cancel();
event.getServletContext().log("定时器销毁");
}
}
一个继承于TimerTask的一个类:StatisticsTask.java
packagecom.ed.cnc.city;
imp<wbr>ortjava.util.Calendar;</wbr>
imp<wbr>ortjava.util.TimerTask;</wbr>
imp<wbr>ortjavax.servlet.ServletContext;</wbr>
/***//**
*统计任务
*@authorwestd
*
*/
publicclassStatisticsTaskextendsTimerTask
{
privatestaticfinalintSTATISTICS_SCHEDULE_HOUR=0;
privatestaticbooleanisRunning=false;
privateServletContextcontext=null;
publicStatisticsTask(ServletContextcontext)
{
this.context=context;
}
@Override
publicvoidrun()
{
Calendarcal=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("上一次任务执行还未结束");
}
}
/***//**
*执行任务
*/
publicvoidexecuteTask()
{
System.out.println("任务1");
System.out.println("任务2");
}
}
web.xml中添加如下代码:
<listener>
<listener-class>com.ed.cnc.servletListener.StatisticsContextListener</listener-class>
</listener>