How to set timer in Java
In this article, you will be very well equipped with the knowledge to set timer in java. The timer in java can be set by using timer class provided by java.util package.
Timer class in Java
The Java class Timer is part of the java.util package. The Serializable interface is implemented, and it inherits the Object class. The constructors and techniques available from the class can be leveraged for time-related tasks. The task that we want to perform at a specific time can be scheduled using the Timer class.
A thread can schedule a job, such as execute a portion of code after a set interval of time, by calling a method provided by the timer class. Each task has the option of being assigned to execute once or repeatedly. Each timer object has a background thread attached to it that is in charge of carrying out all of the tasks.
Note: It is thread-safe to use the Timer class. It implies that a thread is required to access a timer class method. It's also important to notice that the class stores its tasks in a binary heap data structure.
Constructors
Several constructors leverage in the process of setting the timer are as follows
Timer() : builds a new timer.
Timer(String name): introduces a new timer with the supplied name as its associated thread.
Timer(Boolean isdaemon): generates a new timer with the option for its associated thread to function as a daemon.
Timer(String name, Boolean is daemon): Establishes a new timer with the supplied name and the option to function as a daemon. The related thread also has that name.
Methods
cancel(): java.util.Timer.cancel() This timer is ended, and all planned tasks are deleted. does not conflict with a task that is already running (if it exists). A timer's execution thread gracefully ends once it has been stopped, and no more jobs may be performed on it.
Let us understand the basic programs that are related to the timer class
File mane: Timer1.java
// Java programme that displays a schedule Timer class's AtFixedRate function
import java.util.Timer;
import java.util.TimerTask;
import java.util.*;
class Helper extends TimerTask
{
public static int i = 5;
public void run()
{
System.out.println(i--);
if(i ==0 )
{
synchronized(Test.obj)
{
Test.obj.notify();
System.out.print("Its morning! Wake up");
}
}
}
}
public class Timer1
{
protected static Timer1 obj;
public static void main(String[] args) throws InterruptedException
{
obj = new Timer1();
// making a new timer class instance
Timer timer = new Timer();
TimerTask task = new Helper();
//A date object instance for fixed-rate execution
Date date = new Date();
timer.scheduleAtFixedRate(task, date, 500);
System.out.println("Timer running");
synchronized(obj)
{
// the primary thread to wait
obj.wait();
// After the task has been scheduled four times by the timer, the main thread restarts and //the timer is ended.
timer.cancel();
// All operations that have been aborted are removed out from timer'stack queue using
//purge.
System.out.println(timer.purge());
}
}
}
Output:
Timer running
5
4
3
2
1
Its morning! Wake up
File name: Timer3.java
import java.util.Timer;
import java.util.TimerTask;
public class Timer3
{
Timer timer = new Timer();
Timer3(int seconds)
{
//schedule the task
timer.schedule(new RemindTask(), seconds*100);
}
class RemindTask extends TimerTask
{
public void run()
{
System.out.println("Person texted you!");
//terminate the timer thread
timer.cancel();
}
}
//driver code
public static void main(String args[])
{
//function calling
new Timer3(10);
}
}
Output:
Person texted you!
File name: Timer2.java
import java.util.Timer;
import java.util.TimerTask;
class Task extends TimerTask
{
int counter;
public Task()
{
counter = 0;
}
public void run()
{
counter++;
System.out.println("Ring " + counter);
}
public int getCount()
{
return counter;
}
}
public class Timer2
{
private boolean running;
private Task task;
private Timer timer;
public Timer2()
{
timer = new Timer(true);
}
public boolean isRinging()
{
return running;
}
public void startRinging()
{
running = true;
task = new Task();
timer.scheduleAtFixedRate(task, 0, 3000);
}
public void doIt()
{
running = false;
System.out.println("Rang" + task.getCount() + " times");
task.cancel();
}
public static void main(String args[])
{
Timer2 phone = new Timer2();
phone.startRinging();
try
{
System.out.println("Someone is calling...");
Thread.sleep(20000);
}
catch (InterruptedException e)
{
}
phone.doIt();
}
}
Output:
Person is calling...
Ring 1
Ring 2
Ring 3
Ring 4
Ring 5
Ring 6
Ring 7
Rang 7 times