×

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

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

How to Convert String to Integer in Java

How to convert String to int in Java You need to convert String into int if you want to perform a mathematical operation on string which contains digits. To do so,...

3 minutes read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

How many ways to create object in Java?

In this article, you will be acknowledged about the different ways to create an object in java. So far you construct an object from a class, as is common knowledge,...

6 minutes read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.

Literals in Java

In this article we acknowledge ourselves about the term literals in java, types of literals and an example to each of them. Literal Literal refers to any constant value that can be...

4 minutes read.

Java Thread class

Thread class The thread represents a part of the process. Every process can have multiple associated threads in which every thread may execute the same or different job. By default, each thread assigns...

16 minutes read.

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

Java Full Stack

A person who can create both the front end and back end of an application is a full-stack developer. In essence, the term "Java full-stack" refers to a web developer...

9 minutes read.

Java Finally Keyword

The final block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java finally block has...

3 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

Method Overloading In Java

If the same class consists of different methods with the same name and the methods can vary by different number of parameters then it is known as Method Overloading. Method...

2 minutes read.

Java String Concatenation

Java String Concatenation Java programming provide a way to combine multiple strings into a single string. It is called as String Concatenation. There are different ways to concatenate two or more...

4 minutes read.

Java Integer reverse() method

The reverse() method of Java Integer class returns the value obtained by reversing the order of the bits in the 2’s complement binary representation. Syntax public static int reverse (int i)  Parameters The parameter...

1 minute read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

Java Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.