我对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秒。
任何帮助将非常感谢,谢谢!
似乎工作,谢谢! – menackin