The Timer class schedules a task to run at a given time once or repeatedly. It can also run in the background as a daemon thread. To associate Timer with a daemon thread, there is a constructor with a boolean value. The Timer schedules a task with fixed delay as well as a fixed rate. In a fixed delay, if any execution is delayed by System GC, the other execution will also be delayed and every execution is delayed corresponding to previous execution. In a fixed rate, if any execution is delayed by System GC then 2-3 execution happens consecutively to cover the fixed rate corresponding to the first execution start time. The Timer class provides a cancel() method to cancel a timer. When this method is called, the Timer is terminated. The Timer class executes only the task that implements the TimerTask.
Example
import java.util.*;
public class TimerThreadTest {
public static void main(String []args) {
Task t1 = new Task("Task 1");
Task t2 = new Task("Task 2");
Timer t = new Timer();
t.schedule(t1, 10000); // executes for every 10 seconds
t.schedule(t2, 1000, 2000); // executes for every 2 seconds
}
}
class Task extends TimerTask {
private String name;
public Task(String name) {
this.name = name;
}
public void run() {
System.out.println("[" + new Date() + "] " + name + ": task executed!");
}
}Output
[Thu Aug 01 21:32:44 IST 2019] Task 2: task executed! [Thu Aug 01 21:32:46 IST 2019] Task 2: task executed! [Thu Aug 01 21:32:48 IST 2019] Task 2: task executed! [Thu Aug 01 21:32:50 IST 2019] Task 2: task executed! [Thu Aug 01 21:32:52 IST 2019] Task 2: task executed! [Thu Aug 01 21:32:53 IST 2019] Task 1: task executed! [Thu Aug 01 21:32:54 IST 2019] Task 2: task executed! [Thu Aug 01 21:32:56 IST 2019] Task 2: task executed! [Thu Aug 01 21:32:58 IST 2019] Task 2: task executed! [Thu Aug 01 21:33:00 IST 2019] Task 2: task executed!