Java: scheduling a task at random intervals

I am new to Java, and I am trying to create a task that will run every 5-10 seconds, so at any interval in the area from 5 to 10, including 10.

I tried a few things, but so far nothing is working. My last effort 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(); } } 

The "task" is TimerTask. I get:

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

I understand from here that TimerTask cannot be reused, but I'm not sure how to fix it. By the way, my TimerTask is quite complicated and lasts at least 1.5 seconds.

Any help would be really appreciated, thanks!

+6
source share
2 answers

to 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(); } } 
+12
source

Create a new Timer for each task, as you have already done: timer= new Timer();

And if you want to synchronize your code with your streaming tasks, use semaphores rather than sleep(10000) . This may work if you are lucky, but it is definitely wrong because you cannot be sure that your task is truly complete.

+1
source

All Articles