Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if a TimerTask takes longer to execute than the specified interval?

Tags:

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?

like image 466
Ovesh Avatar asked Feb 15 '10 07:02

Ovesh


People also ask

What is the relationship between Timer and TimerTask?

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.

What is period in TimerTask?

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.

How does TimerTask work in Java?

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.

How do you stop a TimerTask?

In order to cancel the Timer Task in Java, we use the java. util. TimerTask. cancel() method.


1 Answers

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).

like image 113
Joonas Pulakka Avatar answered Oct 20 '22 08:10

Joonas Pulakka