2014-01-30 76 views
-1

我會鏈接從我的線程中每5秒執行一次方法。我班的輪廓如下。從Java線程中運行計時器

private static Timer timer = new Timer(); 

public class myThread implements Runnable { 

    public void run() { 

     //listens for incoming messages 
     while(true) { 

      //process queue 
      timer.schedule(new TimerTask() { 
      process_queue(); 
      }, 5*1000); 
     } 
    } 

    public static void process_queue() { 
     //processes queue 
     System.out.println("boom"); 

    } 
} 

任何幫助,將不勝感激。

+0

你面臨什麼問題? –

+0

我需要能夠不斷偵聽傳入消息,但每隔5秒從數據庫處理隊列。我在while循環中運行定時器時遇到問題。 – hawx

+1

重複安排一次任務。您調用'schedule'的線程無關緊要,'Timer'爲計劃任務維護自己的線程。 –

回答

0

所以你的代碼問題就在這裏:

//listens for incoming messages 
while(true) { 

    //process queue 
    timer.schedule(new TimerTask() { 
    process_queue(); 
    }, 5*1000); 
} 

的是,它是要安排無限的任務 - 這是產卵,所有打算在5秒鐘後運行的任務無限循環。

嘗試這樣:

public void run() { 

     //listens for incoming messages 
     while(true) { 
      process_queue(); 
      sleep(5000); //watch out for Exception handling (i.e. InterruptedException) 
     } 
    } 

雖然在今天的軟件發展趨勢,你想避免blocking等待(即睡眠()方法塊當前線程)。見Akka Actors - http://akka.io/

你也說你想每隔5秒運行一次方法,但need to be able to constantly listen for incoming messages。你能澄清嗎?乾杯