2011-03-12 33 views
0

我運行一個IRC bot,它需要在兩個集小時的聊天呼應的消息,爲此,每隔幾分鐘:執行的方法來檢查的時間和特定的時間執行的方法

我試圖做的:

 public void timerTest(int minH,int maxH, int minT){ 
     boolean b = true; 
     boolean timeout = false; 
     while(b){ 
      while(!timeout){ 
       if(c.get(Calendar.HOUR_OF_DAY) >= minH && c.get(Calendar.HOUR_OF_DAY) <= maxH && c.get(Calendar.MINUTE) % minT == 0){ 
        sendMessage(channel,spam1.getMessage()); 
        timeout = true; 
        } 
       } 
       if(c.get(Calendar.MINUTE)%minT == 1){ 
        timeout = false; 
       } 
      } 
     } 

我常想垃圾郵件的郵件2-6之間,每15分鐘我試圖把它在unendless while循環,但不建議這樣做。我尋找Timer和TimerTask,但我無法弄清楚如何正確地做到這一點。如果有人會如此善意地解釋我如何實現這一目標?

謝謝^^

+0

顯示如何創建'c' – adarshr 2011-03-12 16:16:45

+0

,並且您帖子右側的「相關問題」都無法幫助您? – smas 2011-03-12 16:21:09

+0

爲什麼不推薦使用循環? – 2011-03-12 16:23:49

回答

1

的Java TimerTimerTask不是真能勝任複雜的調度需求,如你的。

我會建議您調查quartz。它允許你安排例如使用cron表達式,這是非常強大的。我認爲像下面的表達式可能是有用的:

*/15 2-6 * * * ? 
+0

謝謝,它似乎令人難以置信的強大,將玩一段時間:p – 2011-03-12 16:43:51

+0

我仍然有一個問題,雖然我正在運行我的IRCbot但它仍然需要能夠定期在類中運行一個方法,因爲它使用另一種方法來自另一個只能被初始化一次的對象。但我似乎只能安排一堂課? – 2011-03-12 17:21:26

+0

@Lucas,你實現了'job'接口,它可以讓你運行一個方法。參見['例子1 - 你的第一個Quartz程序](http://www.quartz-scheduler.org/docs/examples/Example1.html) – 2011-03-12 18:32:05

0

一個非常簡單的想法可能是使用Spring和做這個任務 任務框架看一看 http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html

你可以簡單地註釋你的類方法與 @Scheduled(cron = "*/15 2-6 * * * ?")

或者,如果你不希望包括Spring的依賴,你可以創建的ScheduledThreadPoolExecutor

實例
// set the poolsize to 1 
    ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1); 
    scheduler.scheduleWithFixedDelay(new Runnable() { 
     @Override 
     public void run() { 
      // call method 
     } 
    }, 2,2, TimeUnit.HOURS); 

這使您能夠靈活地安排可以定期調用您的方法的runnable。確保在應用程序關閉時關閉執行程序,否則應用程序可能會掛起。