×

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

Related Topics

Java Math tan() Method

The tan() method of Java Math class returns the trigonometric tangent of the specified angle. Syntax: public static double tan(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The tan() method...

2 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

3 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

Nth node from the end of the Linked list in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

6 minutes read.

Zygodromes in Java

Zygodrome is a positive number created by the same digits running non-trivially. A number is called a zygodrome if identical digits constantly occur together (in pairs). The Greek word "zyg"...

4 minutes read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

8 minutes read.

Java Integer doubleValue() method

The doubleValue() method of Integer class returns a double value for this Integer after a widening primitive conversion. Syntax public double doubleValue() Parameters NA Specified by This method is specified by doubleValue in class Number Return Value This...

1 minute read.

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.

Object Definition in Java

In this article, you will be acknowledged about object in Java, its definition and how is this useful in writing the programs in Java. The comprehension of object-oriented technology depends on...

4 minutes read.

Computing Digit Sum of all Numbers from 1 to n in Java

In this tutorial, we will discuss various methods to compute the sum of digits of all numbers beginning from 1 to n through a Java program. We will achieve it through...

7 minutes read.

Minimum Lights to Activate Java Snippet Class

Minimum Lights to Activate Problem in Java In prison, there is a hallway that is N units long. Given an N-dimensional array A. If the light at the ith position is...

3 minutes read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.

Various operations on the Queue using Stack in Java

The Java Collections Framework's core data structures are the Stack and Queue. They are used to store and retrieve identical data in a presentation sequence. These two linear data structures...

7 minutes read.

Dictionary in Java

Dictionary in Java The Dictionary class represents a key-value relation which maps keys to values. In Dictionary class, every key and every value is an object. It is an abstract class associated with...

2 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Java String replace() method

Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence. Syntax: public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) Parameters: oldChar...

2 minutes read.

Java String toUpperCase() methods

Java String toUpperCase() method is used to convert all the characters of the String into upper case. Syntax public String toUpperCase() public String toUpperCase(Locale locale) Returns It returns upper case String. Java String toUpperCase() Example 1: public...

1 minute read.

Count of Range Sum Problem in Java

In this article, we will discuss the basic approach or native approach used to count range sum problem in java. To solve this problem, we will check for numbers if they...

6 minutes read.

Resultset in java

Resultset: A result set is an interface that is present in the package java.sql and the resultset is used to store the data that are returned from the database table after...

5 minutes read.