Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Scheduling a task in random intervals

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!

like image 961
idpolitis Avatar asked Jan 18 '13 16:01

idpolitis


1 Answers

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();
    }
}
like image 181
Evgeniy Dorofeev Avatar answered Sep 20 '22 21:09

Evgeniy Dorofeev