Java: Scheduling a task in random intervals

雨燕双飞 提交于 2019-11-30 15:23:06

问题


I am quite new to Java and I'm trying to generate a task that will run every 5 to 10 seconds, so at any interval in the area between 5 to 10, including 10.

I tried several things but nothing is working so far. My latest effort is below:

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" is a TimerTask. What I get is:

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

I understand from here that a TimerTask cannot be reused, but I am not sure how to fix it. By the way the my TimerTask is quite elaborate and lasts itself at least 1,5 seconds.

Any help will be really appreciated, thanks!


回答1:


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



回答2:


Create a new Timer for each task instead, like you already do: timer= new Timer();

And if you want to synchronize your code with your threaded tasks, use semaphores and not sleep(10000). This might work if you're lucky, but it's definitely wrong because you cannot be sure your task has actually finished.



来源:https://stackoverflow.com/questions/14403320/java-scheduling-a-task-in-random-intervals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!