This tutorial explains how to use the Java Timer Class to set a timer in Java with programming examples:
In this tutorial, we are going to explore Java.util.Timer class. We will mainly focus on the declaration, description, constructors, and methods that this class supports. We will also come up with examples that will help you understand the topic better.
Some frequently asked questions will also be provided as a part of the tutorial to help you in knowing the trending questions that are asked related to the Java Timer Class.
=> Visit Here To Learn Java From Scratch
Table of Contents:
Java.util.Timer Class
Also, many threads can share a single Java Timer class object, thereby making it thread-safe. All the tasks of a Java Timer class are stored in the binary heap.
Syntax:
public class Timer extends Object
Constructors With Description
Timer(): Every time, it creates a new Timer. The below constructors are the variations of it.
Timer(boolean isDaemon): It creates a new Timer whose thread has been specified to run as daemon thread.
Timer(String name): It creates a new Timer whose thread has already given a name.
Timer(String name, boolean isDaemon): It creates a new Timer whose thread has a name specified, and also it is defined to run as a daemon thread.
Timer Methods
Given below are the methods with the description that the Java Timer class supports.
- void cancel(): This method terminates the current or this Timer and also cancels all the tasks that are currently scheduled.
- int purge(): After cancellation, the purge() method removes all the canceled tasks from the queue.
- void schedule(TimerTask task, Date time): It lines up the task that is to be executed at a specified time.
- void schedule(TimerTask task, Date firstTime, long period): It also lines up the task with a specified start time and then the task undergoes repeated execution.
- void schedule(TimerTask task, long delay): It also lines up the task for execution after the delay.
- void schedule(TimerTask task, long delay, long period): It also lines up the task for repeated execution but it starts with a specified delay.
- void scheduleAtFixedRate(TimerTask task, Date firstTime, long period): It also lines up the task for repeated fixed-rate execution and the task starts at a specified time.
- void scheduleAtFixedRate(TimerTask task, long delay, long period): It also lines up the task for repeated but at fixed-rate execution and the task starts with a specified delay.
Java Timer Schedule() Example
Here is an example of the Java Timer that includes the functionality of scheduling the specified task for repeated execution with a fixed delay and the task has some specified start time.
First of all, we have declared a Helper class that is extending TimerTask class. Inside this TimerTask, we have initialized a variable that will be used to check the number of counts of the execution.
The run() method of TimerTask class is used to print the number of times the execution is done. In the main method, we have used the “void schedule(TimerTask task, Date firstTime, long period)” variation of the schedule() method to execute the run() method as many times as we want.
We explicitly need to stop the execution otherwise the run() method will keep on executing.
import java.util.Timer; import java.util.TimerTask; class Helper extends TimerTask { public static int i = 1; // TimerTask.run() method will be used to perform the action of the task public void run() { System.out.println("This is called " + i++ + " time"); } } public class example { public static void main(String[] args) { Timer timer = new Timer(); // Helper class extends TimerTask TimerTask task = new Helper(); /* * Schedule() method calls for timer class. * void schedule(TimerTask task, Date firstTime, long period) */ timer.schedule(task, 200, 5000); } }
Output:
Java Timer Cancel() Example
Here is an example of the Java Timer class that includes the functionality of the cancel() method. As we know, the cancel() method is used to terminate this Timer and also discards any scheduled tasks but it does not interfere with any currently executing task or action.
In this example, we will see that the statement inside for loop will keep on executing even after the first “Stop calling” statement is encountered i.e. ‘i’ became equal to 3.
Now we will move on to the example of the purge() method given below.
import java.util.*; public class example { public static void main(String[] args) { Timer timer = new Timer(); TimerTask task = new TimerTask() { // run() method to carry out the action of the task public void run() { for(int i=1; i<= 10; i++) { System.out.println("Keep on calling"); if(i >= 3) { System.out.println("Stop calling"); // cancel method to cancel the execution timer.cancel(); } } }; }; /* * schedule() method to schedule the execution with start time */ timer.schedule(task, 5000, 5000); } }
Output:
Java Timer Purge() Example
If you compare the example given for cancel() and purge() methods, you will notice that in the below example of the purge() method, a break statement has been put just after the cancel() method. This will allow the control to come out of the loop as soon as ‘i’ becomes 3.
Now that we have come out of the loop, we have tried to return the number of tasks removed from the queue. For this, we have simply called the method purge with the help of a reference variable.
import java.util.*; public class example { public static void main(String[] args) { Timer timer = new Timer(); TimerTask task = new TimerTask() { // run() method to carry out the action of the task public void run() { for(int i=1; i<= 10; i++) { System.out.println("Keep on calling"); if(i >= 3) { System.out.println("Stop calling"); // cancel method to cancel the execution timer.cancel(); break; } } // Purge after cancellation System.out.println("Purge " + timer.purge()); }; }; /* * schedule() method to schedule the execution with start time */ timer.schedule(task, 5000, 5000); } }
Output:
Frequently Asked Questions
Q #1) What is the Timer class in Java?
Answer: The Timer class in Java belongs to Java.util.Timer package that provides a facility for threads to schedule a task that will be executed in the future in a background thread.
Q #2) Is Java Timer a thread?
Answer: Java Timer is a class whose object is associated with a background thread.
Q #3) How do I stop a timer in Java?
Answer: You can use the cancel() method if you want to terminate this Timer and also cancel any currently scheduled tasks.
Q #4) What does the timer do in Java?
Answer: It provides a facility for threads to schedule a task that will be executed in the future in a background thread.
Q #5) Is TimerTask a thread?
Answer: TimerTask is an abstract class. It implements the Runnable interface because the instance of this class is intended to be run by the threads. So, the implementation of TimerTask class is a thread.
Conclusion
In this tutorial, we have learned about Java.util.Timer class. All the necessary information related to the Timer class like the declaration, description, methods that Timer class supports, constructors, etc., have been included here.
Also, we have given ample programs for each of the methods that will give you a better understanding of each method. Some frequently asked questions have been provided just to make sure that you are aware of the trending questions.
=> Check Here To See A-Z Of Java Training Tutorials