2013-01-18 65 views
6

我對Java很新,我試圖生成一個每5到10秒運行一次的任務,因此在5到10之間的任何區間,包括10個。Java:隨機調度任務

我嘗試了幾件事,但沒有任何工作到目前爲止。我最近的努力如下:

timer= new Timer(); 
Random generator = new Random(); 
int interval; 

//The task will run after 10 seconds for the first time: 
timer.schedule(task, 10000); 

//Wait for the first execution of the task to finish:    
try { 
    sleep(10000); 
} catch(InterruptedException ex) { 
ex.printStackTrace(); 
} 

//Afterwards, run it every 5 to 10 seconds, until a condition becomes true: 
while(!some_condition)){ 
    interval = (generator.nextInt(6)+5)*1000; 
    timer.schedule(task,interval); 

    try { 
     sleep(interval); 
    } catch(InterruptedException ex) { 
    ex.printStackTrace(); 
    } 
} 

「task」是一個TimerTask。我得到的是:

Exception in thread "Thread-4" java.lang.IllegalStateException: Task already scheduled or cancelled 

我從here是一個TimerTask不能重用理解,但我不知道如何解決它。順便說一下,我的TimerTask是相當複雜的,並持續至少1.5秒。

任何幫助將非常感謝,謝謝!

回答

12

嘗試

public class Test1 { 
    static Timer timer = new Timer(); 

    static class Task extends TimerTask { 
     @Override 
     public void run() { 
      int delay = (5 + new Random().nextInt(5)) * 1000; 
      timer.schedule(new Task(), delay); 
      System.out.println(new Date()); 
     } 

    } 

    public static void main(String[] args) throws Exception { 
     new Task().run(); 
    } 
} 
+1

似乎工作,謝謝! – menackin

1

爲每個任務新Timer相反,像你已經這樣做了:timer= new Timer();

如果你想你的代碼與線程任務同步,使用信號量和不sleep(10000)。如果你幸運的話,這可能會奏效,但這絕對是錯誤的,因爲你不能確定你的任務已經完成。

+0

謝謝您的答覆。我只有一個任務會一個接一個地運行預定義的次數。你認爲我還需要使用信號量嗎?另外,如果我爲任務運行的每個時間創建一個新的計時器,這是否意味着我需要一組定時器或類似的東西? – menackin

+0

你說你想等第一個任務結束。這需要一個信號量。如果你不想要,你不需要跟蹤定時器。它們將在晚些時候由GC自動釋放。 – m0skit0