# How can we implement a timer thread in Java?

JavaObject Oriented ProgrammingProgramming

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 static void main(String []args) {
Timer t = new Timer();
t.schedule(t1, 10000); //  executes for every 10 seconds
t.schedule(t2, 1000, 2000); // executes for every 2 seconds
}
}
private 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:33:00 IST 2019] Task 2: task executed!