
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
Timer Class in Java
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 Name | Description |
---|---|
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 name | Description |
---|---|
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. |
void schedule(TimerTask task, Date time) | It schedules the specified task for execution at the specific time. |
void schedule(TimerTask task, Date firstTime, long period) | It schedules the specified task for repeated fixed-delay execution which begins at the specified time. |
void schedule(TimerTask task, long delay) | It schedules the specified task for execution in Java after a given delay. |
void schedule(TimerTask task, long delay, long period) | It schedules the specified task for repeated fixed-delay execution which begins after the specified delay. |
void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) | It schedules the specified task for repeated fixed-rate execution, which begins at the specified time. |
void scheduleAtFixedRate(TimerTask task, long delay, long period) | It schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. |