What is a Timer class in Java?

Javathreadstimer

A Java.util.Timer is a utility class used to schedule a task to be executed after a specific amount of time. Tasks can be scheduled for one-time execution or for repeated execution periodically.

Multiple objects of the Timer class can be created but there is a single background thread monitoring the execution of each Timer’s tasks.

Note: The Timer class is thread-safe i.e. multiple threads can share a single timer without the use of any synchronization.

svg viewer

Timer class

An object of the timer class can be created as follows:

Timer timer = new Timer();

Constructors

Java provides a variety of parameterized constructors for the Timer object. Let’s look at each of them:

1. Timer(): The default constructor of the Timer class which creates an object of the class.

2. Timer(boolean isDaemon): This parameterized constructor creates a new timer whose associated thread may be specified to run as a daemon.

3. Timer(String name): Creates a new timer whose associated thread has the specified name.

4. Timer(String name, boolean isDaemon): Creates a new timer whose associated thread has the specified name, and may be specified to run as a daemon.

Note: Deamon is a low priority task that runs in the background to perform minor tasks such as garbage collection.

Class methods

In addition to parameterized constructors, Java also provides a number of helper functions with the timer class. Let’s look at some of the most frequently used functions:

1. cancel(): Terminates this timer, discarding any currently scheduled tasks.

2. schedule(TimerTask task, Date time): Schedules the specified task for execution at the specified time.

3. purge(): Removes all canceled tasks from this timer’s task queue.

Example

Let’s take an example of using a Timer to execute a task after a specific interval of time:

Note: The java.util.Timer class must be imported for the Timer class to function.

import java.util.Timer;
import java.util.TimerTask;

class Notifier {
    Timer timer;

    public Notifier(int seconds) {
        timer = new Timer();
        timer.schedule(new RemindTask(), seconds*1000); // schedule the task
    }

    class RemindTask extends TimerTask {
        public void run() {
            System.out.println("You have a notification!");
            timer.cancel(); //Terminate the timer thread
        }
    }

    public static void main(String args[]) {
        new Notifier(5);
    }
}