1 java.util.Timer
這個方法應該是最常用的,不過這個方法需要手工啟動你的任務:
Timer timer=new Timer();
timer.schedule(new ListByDayTimerTask(),10000,86400000);
這里的ListByDayTimerTask類必須extends TimerTask里面的run()方法。
2 ServletContextListener
這個方法在web容器環境比較方便,這樣,在web server啟動后就可以自動運行該任務,不需要手工操作。
將ListByDayListener implements ServletContextListener接口,在contextInitialized方法中加入啟動Timer的代碼,在contextDestroyed方法中加入cancel該Timer的代碼;然后在web.xml中,加入listener:
3 org.sPRingframework.scheduling.timer.ScheduledTimerTask
假如你用spring,那么你不需要寫Timer類了,在schedulingContext-timer.xml中加入下面的內容就可以了:
新聞熱點
疑難解答