2013-01-18 62 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