2012-03-14 30 views
1

我有一個在tomcat啓動時啓動的servlet。我需要在該servlet中的一項功能,在定期的時間間隔後觸發事件,即1小時和 在後臺運行?這裏是我的代碼: -Servlet在啓動時使用timer類在常規時間間隔後觸發事件嗎?

在main方法

MyTask contentTask = new MyTask(); 
long interval = 60 * 60 * 1000; 
Timer timer = new Timer(); 
timer.schedule(contentTask, new Date(), interval);//line 1 
System.out.println("line2");//line2 

MyTask

public class MyTask extends TimerTask { 
@Override 
public void run() { 
System.out.println("Inside my task"); 

} 
} 

我正在儘快控制期待來到2號線,運行方法被執行,然後不斷execting的60分鐘後的任務像後臺線程那樣。但是 控制不會在第2行之後運行方法。我不確定我在這裏丟失了什麼以及爲什麼run方法沒有得到執行?

編輯: - 我認爲問題是間隔值,如果我使它1分鐘,即1 * 60 * 1000;控制來運行的方法。看起來即使第一次任務將在指定的時間間隔後執行,即60分鐘,但是我希望在執行第1行後立即執行任務,然後在60分鐘後重復執行該任務。

+0

你試過用500ms延遲開始時間嗎?像'timer.schedule(contentTask,new Date(new Date()。getTime()+ 500),interval)'? – Nishant 2012-03-14 06:09:47

回答

0

在我看來,你正在尋找一個ServletContextListener。您可以在部署之前執行代碼。在此代碼中,您使用Executors而不是「Vanilla」線程,並安排它。

@WebListener 
public class GlobalContext implements ServletContextListener { 
    private ServletContext app; 
    private ScheduledExecutorService scheduler; 

    //What to do when app is deployed 
    public void contextInitialized(ServletContextEvent event) { 
     //Init Context 
     app = event.getServletContext(); 
     //In my case I store my data in the servlet context with setAttribute("myKey", myObject) 
     //and retrieve it with getAttribute("myKey") in any Servlet 

     // Scheduler 
     scheduler = Executors.newSingleThreadScheduledExecutor(); 
     scheduler.scheduleAtFixedRate(new AutomateRefresh(), 0, 60, TimeUnit.MINUTES);  
    } 

    //Do not forget to destroyed your thread when app is destroyed 
    public void contextDestroyed(ServletContextEvent event) { 
     scheduler.shutdown(); 
    } 

    //Your function 
    public class AutomateRefresh implements Runnable { 
     public void run() { 

      //Do Something 

     } 
    } 

} 

僅供參考,執行程序是Java 5及更高版本的一部分。

相關問題