When using
Timer.schedule(TimerTask task, long delay, long period)
(i.e. with fixed-delay execution), what happens if the specified TimerTask
's run()
method takes longer than period
to complete? Is it possible that two concurrent TimerTask
threads will be running because of this?
And if so, is there a way to avoid it?
Timer
andTimerTask
don't handle this sort of situation well. If you want to handle it better, then don't use those classes.java.util.concurrent.ScheduledExecutorService
provides two scheduling methods,scheduleAtFixedRate
andscheduledWithFixedDelay
, which govern what happens when tasks "bunch up".scheduleAtFixedRate
:scheduleWithFixedDelay
:You can create
ScheduledExecutorService
instances using theExecutors
factory class.Timer's documentation says the following:
That is, concurrent
TimerTask
threads will not be running. The tasks will accumulate into a queue. This may or may not be appropriate (more likely, not).