Timer Class in Java

Java 8Object Oriented ProgrammingProgramming

The Timer Class in Java is a facility for threads to plan tasks for future execution in a background thread. Tasks may be executed a single time or multiple times. The Timer class is thread-safe i.e. the threads of the class do not require external synchronization and can share a single Timer object. A point to be noted is that all constructors start a Timer thread.

The Timer Class in Java came into existence since JDK 1.3. This class ascends up to large numbers of concurrently scheduled tasks. Internally, it uses a binary heap in the memory to represent its task queue, so the time complexity to scheduling a task is O(log n), where n is the number of concurrently scheduled tasks.

Declaration - The java.util.Timer class is declared as follows −

public class Timer extends Object

Let us have a look at the constructors of the class.

Constructor NameDescription
Timer()This constructor creates a new timer.
Timer(boolean isDaemon)This constructor creates a new timer whose linked thread may be described to execute as a daemon
Timer(String name)This constructor creates a new timer whose linked thread has the name specified in the argument
Timer(String name, boolean isDaemon)This constructor creates a new timer whose linked thread has the name specified in the argument and maybe described to run as a daemon.

Here are the methods of the Timer class.

Method nameDescription
void cancel()It is used to terminate the current timer and gets rid of any presently scheduled tasks
int purge()It removes all the cancelled tasks from the timer's task queue.