依據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>