依据Java自身提供的接口实现,经过监听器(Listener)和定时器(Timer)定时执行某个任务(Task)。java
1.定义MyListener:web
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:code
importjava.util.TimerTask; publicclassMyTaskextendsTimerTask { publicvoidrun() { // System.out.println("call at " + (new Date())); //TODO此处添加具体任务代码 } }
3.配置web.xml:xml
<listener> <listener-class>com.fastunit.samples.listener.MyListener</listener-class> </listener>