Java: Scheduling a task in random intervals

2019-02-13 21:44发布

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!

2条回答
地球回转人心会变
2楼-- · 2019-02-13 22:21

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();
    }
}
查看更多
太酷不给撩
3楼-- · 2019-02-13 22:32

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.

查看更多
登录 后发表回答