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 provides method to schedule Task where the task is an instance of TimerTask class, which implements the Runnable interface and overrides run() method to define task which is called on scheduled time.
period - time in milliseconds between successive task executions. (Your IDE should also show it to you automatically) So delay is the time from now till the first execution, and after that it executes every period milliseconds again.
TimerTask is an abstract class defined in java. util package. TimerTask class defines a task that can be scheduled to run for just once or for repeated number of time. In order to define a TimerTask object, this class needs to be implemented and the run method need to be overridden.
In order to cancel the Timer Task in Java, we use the java. util. TimerTask. cancel() method.
Timer's documentation says the following:
Timer tasks should complete quickly. If a timer task takes excessive time to complete, it "hogs" the timer's task execution thread. This can, in turn, delay the execution of subsequent tasks, which may "bunch up" and execute in rapid succession when (and if) the offending task finally completes.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With