Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java timer scheduled tasks

Tags:

java

timer

What happens in the following case?

Timer t = new Timer();
t.schedule(...);
t = new Timer();

Specifically, what happens to the the tasks that I've scheduled on Timer t after I've assigned a new instance of Timer to t?

like image 947
lgp Avatar asked Jul 12 '11 15:07

lgp


People also ask

What does timer task do in Java?

Java programming language provides a class utility known as Timer Task. It allows one to schedule different tasks. In other words, a task can be executed after a given period or at a specified date and time. A Timer in Java is a process that enables threads to schedule tasks for later execution.

Can you add a timer in Java?

The Java language libraries include a "swing timer," which lets you add a countdown timer on your Java forms. You set up the timer's properties such as the amount of time that passes before a function triggers. The timer continually runs, so you can trigger a function continuously in your application.

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.


1 Answers

They doesn't go away. Each Timer object is associated with a background process. Even when you remove all references to your Timer in your program, the background process will still continue to run (it holds it's own reference to the object). Because of this, the object will not be subject to garbage collection.

See the official documentation for details.

Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially ... After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can take arbitrarily long to occur.

like image 127
tskuzzy Avatar answered Sep 24 '22 23:09

tskuzzy