我对 Java 很陌生,我正在尝试生成一个每 5 到 10 秒运行一次的任务,因此可以在 5 到 10 秒之间的任何时间间隔运行,包括 10 秒。
我尝试了几件事,但到目前为止没有任何效果。我最新的努力如下:
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();
}
}
“任务”是一个TimerTask。我得到的是:
Exception in thread "Thread-4" java.lang.IllegalStateException: Task already scheduled or cancelled
我的理解是从hereTimerTask 无法重用,但我不知道如何修复它。顺便说一句,我的 TimerTask 非常复杂,持续时间至少为 1.5 秒。
任何帮助将不胜感激,谢谢!
try
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();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)