Resolving this will be error prone, as task0 can still work when resubmitted by another timer. (Note that cancel() does not complete the task.)
Note that if task0 controlled by a single Timer , the same task will never be executed simultaneously with itself (regardless of whether it runs with a fixed delay or a fixed speed).
If you really want this behavior, the job should be to let task0 and task1 wrap the shared object:
class Task extends TimerTask { Runnable runnable; Task(Runnable runnable) { this.runnable = runnable; } @Override public void run() { runnable.run(); } }
And then do it like this:
// "Wrapped" (and thus shared) by task0 and task1 below. Runnable runnable = new Runnable() { @Override public void run() { System.out.println("task was invoked"); } } Timer timer0 = new Timer(); Task task0 = new Task(runnable); timer0.schedule(task0, delay); timer0.cancel(); Task task1 = new Task(runnable); Timer timer1 = new Timer(); timer1.schedule(task1, delay); // throws an exception if we use task0 Thread.sleep(5000); timer1.cancel();
aioobe
source share