2013-03-20 82 views
0

我正在使用TimerTask每3秒發送一次消息,但它只發送一次。如何爲PrintWriter設置TimerTask?

public static void main(String[] args) throws IOException { 
      soc = new Socket("localhost", 12345); 
      out = new PrintWriter(soc.getOutputStream(), true); 
      send(); 
     } 
     private static void send() { 
      Timer timer = new Timer(); 
      timer.schedule(new TimerTask() { 
       @Override 
       public void run() { 
        out.println("fetewtewwefwfewf egreg \n"); 
        out.flush(); 
        InputStream is; 
        try { 
         is = soc.getInputStream(); 
         DataInputStream dis = new DataInputStream(is); 
         while (!soc.isClosed()) { 
          long value = dis.readLong(); 
          System.out.println(value); 
         } 
        } catch (IOException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 
       } 
      }, 3000); 
     } 
    } 

回答

1

您正在使用timer.schedule(TimerTask task, long delay),它只爲一次執行計劃任務。對於重複執行使用timer.scheduleAtFixedRate(TimerTask task, long delay, long period),那就是改變你的代碼

timer.scheduleAtFixedRate(new TimerTask() { 
    .... 
}, 0, 3000); 
+0

有什麼不同的B/W'timer.scheduleAtFixedRate(TimerTask的任務,長時間的延遲,週期長)'和'timer.schedule(TimerTask的任務,長延遲,長週期)' – 2013-03-20 09:18:34

+1

是的,timer.schedule()是固定延遲。在上一個任務完成後,下一個任務的執行將按照指定的延遲進行。例如,如果週期= 3秒,任務執行需要1秒,那麼它將每4秒執行一次。 – 2013-03-20 09:26:42

0

你或許應該看看 this link

您正在使用timer.schedule(TimerTask task, long delay)這是越來越調度一次。
對於重複調度,你應該使用timer.schedule(TimerTask task, long delay, long period)

但通過Evgeniy Dorofeev

timer.scheduleAtFixedRate(new TimerTask(){}, 0, 3000); 

的回答是沒有你的任務的執行時間的開銷。並將在下次執行特定的period
雖然timer.schedule(TimerTask t, long d, long period)將包含您的任務執行時間,並且將在您的上一個任務完成後在下一次執行period時執行。