INTRODUCTION:
Java Timer class (java.util.Timer) allows an application to schedule the task on a separate background thread. Please note that by default the associated thread is a non-daemon thread i.e. application does not terminate pending timer thread to complete execution.However, you can change the associated thread to Timer Class as Daemon Thread during creation of Timer Object. (Learn more about Daemon Thread in java)
TIMER TASK:
Timer class needs Timer Task (java.util.TimerTask) (Runnable Object) to execute the task. This is the class where the actual logic implementation resides inside run method. Timer when scheduled, picks up Timer Task and executes (once or repetitive as the case may be).
HOW TO SCHEDULE TASK:
Timer class provides various ways to schedule the task based on number of execution and rate of execution. Here are the list:
HOW JAVA TIMER WORKS INTERNALLY:
Internally Timer uses binary heap data structure to store Timer tasks. The constructor to create Timer object also creates Timer Thread with it and schedule method put the task on binary heap. It works on Object.wait() call to maintain Thread wait and notify.
Timer class is also thread-safe so multiple threads can simultaneously use it.
JAVA TIMER CODE EXAMPLE :
Код:
|
import java.util.Timer;
import java.util.TimerTask;
public class JavaTimer {
public static void main(String[] args){
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Inside Timer Task" + System.currentTimeMillis());
}
};
System.out.println("Current time" + System.currentTimeMillis());
timer.schedule(task, 10000,1000);
System.out.println("Current time" + System.currentTimeMillis());
}
} |
OUTPUT :
Current time1455469505220
Current time1455469505221
Inside Timer Task1455469515222
Inside Timer Task1455469516222
Inside Timer Task1455469517222
Inside Timer Task1455469518222
Inside Timer Task1455469519222
Inside Timer Task1455469520222
Inside Timer Task1455469521222
Inside Timer Task1455469522222
Inside Timer Task1455469523222
Inside Timer Task1455469524222
Inside Timer Task1455469525222
Inside Timer Task1455469526222
Inside Timer Task1455469527222
Inside Timer Task1455469528223
Inside Timer Task1455469529223 and it goes on
ANALYSIS :
The call to timer.schedule(task, 10000,1000) is going to schedule the task which is going to execute for first time (on another thread) after 10 second from this call. After that it will call again after delay of 10 seconds. It is important to mention here that if the task cannot be started after 10 seconds, next task call will not get pre-pond. So here the delay time between two consecutive task is fixed.
Source:
Java Timer Example