Java:以随机间隔调度任务

时间:2013-01-18 16:32:46

标签: java random timer timertask

我是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();
    }
}

“task”是一个TimerTask。我得到的是:

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

我从here了解到TimerTask无法重用,但我不知道如何修复它。顺便说一句,我的TimerTask非常复杂,至少持续1.5秒。

非常感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:13)

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 :(得分:1)

为每项任务创建一个新的Timer,就像您已经做的那样:timer= new Timer();

如果您想将代码与线程任务同步,请使用信号量而不是sleep(10000)。如果你很幸运,这可能会有效,但这肯定是错的,因为你无法确定你的任务是否已经完成。