Java 定时任务的实现

1.定义MyListener:

importjava.util.Timer;
importjavax.servlet.ServletContextEvent;
importjavax.servlet.ServletContextListener;

publicclassMyListenerimplementsServletContextListener{
 privateTimertimer=null;
 publicvoidcontextInitialized(ServletContextEventevent) {
   timer=newTimer(true);
   //设置任务计划,启动和间隔时间
   timer.schedule(newMyTask(), 0, 86400000);
  }
 publicvoidcontextDestroyed(ServletContextEventevent) {
   timer.cancel();
  }
}

2.定义MyTask:

importjava.util.TimerTask;

publicclassMyTaskextendsTimerTask {
 publicvoidrun() {
   // System.out.println("call at " + (new Date()));
   //TODO此处添加具体任务代码
  }
}

3.配置web.xml:

<listener>
<listener-class>com.fastunit.samples.listener.MyListener</listener-class>
</listener>