There are some disadvantages to using a timer
- It creates only one thread to perform tasks, and if the task takes too much time to perform other tasks.
- It does not handle the exceptions set by tasks, and the thread just ends, which affects other scheduled tasks, and they never run.
While on the other hand, it ScheduledThreadPoolExecutorcopes with all these problems correctly, and it makes no sense to use a timer. In your case two methods can be used
scheduleAtFixedRate (...)
scheduleWithFixedDelay (..)
class LongRunningTask implements Runnable {
@Override
public void run() {
System.out.println("Hello world");
}
}
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
long period = 100;
exec.scheduleAtFixedRate(new LongRunningTask (), 0, duration, TimeUnit.MICROSECONDS);
long delay = 100;
exec.scheduleWithFixedDelay(new MyTask(), 0, duration, TimeUnit.MICROSECONDS);
And to cancel the Contractor use this - ScheduledFuture
ScheduledFuture scheduleFuture = exec.scheduleAtFixedRate(new MyTask(), 0, duration, TimeUnit.MICROSECONDS);
... ...
scheduleFuture.cancel(true);
source
share