Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we implement a timer thread in Java?
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
[Wed Nov 22 06:38:50 GMT 2023] Task 2: task executed! [Wed Nov 22 06:38:52 GMT 2023] Task 2: task executed! [Wed Nov 22 06:38:54 GMT 2023] Task 2: task executed! [Wed Nov 22 06:38:56 GMT 2023] Task 2: task executed! [Wed Nov 22 06:38:58 GMT 2023] Task 2: task executed!