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!
source share