Java Timer
Timer
is a service available in the Java programming language that allows users to schedule a future event. These future events can be one time or repeated at regular time intervals. There can be triggers that we use to initiate future events.
Schedule a One-Time Task With Timer
in Java
import java.util.Timer;
import java.util.TimerTask;
public class StopWatch {
Timer timer;
public StopWatch(int seconds) {
timer = new Timer();
timer.schedule(new StopTask(), seconds * 1000);
}
public static void main(String[] args) {
new StopWatch(10);
System.out.println("StopWatch Started.");
}
class StopTask extends TimerTask {
public void run() {
System.out.println("Time Up!");
timer.cancel();
}
}
}
In the above code block, we have created a public class named the StopWatch
class. It has its public constructor, which takes time in seconds. In the constructor block, a timer instance gets created. Over the timer instance, the schedule
method gets called. This method task is to schedule the specific event at the given amount of time. It takes two parameters TimerTask
instance and the delay. We define the delay in milliseconds. The method throws IllegalArgumentException
when the given delay defined is invalid, IllegalArgumentException
when the task provided is already scheduled or canceled. It also throws NullPointerException
when the task instance provided is null.
Just below the constructor, we have the main
method from where the actual execution starts. It creates a new instance of the StopWatch
class with defined delay, which internally executes the statement in the constructor block.
Below the main
method, an inner class named StopTask
is defined that extends a TimerTask
abstract class. TimerTask
is an abstract class that has an abstract method called the run
method. The method needs to get overridden in the StopTask
class, and if not overridden, the class should itself become abstract. Now in the run
method, we have stopped the timer with the cancel
method. The method discards any currently scheduled task and terminates the timer task.
Below is the output of the above code block. The second line gets printed when the delay in the schedule method gets encountered.
StopWatch Started.
Time Up!
Schedule a Repeating Timer in Java
We will modify the above code to create a repeating timer. Repeated timer gets executed repeatedly at regular intervals of time.
In the below code block, we have created a Timer
instance. The instance variable use is to call a method scheduleAtFixedRate
method, which schedules the future events. The method has various implementations. The one we used takes three parameters. First, a TimerTask
instance holds statements related to action we want to perform in the future. Next, the delay
variable defines the time taken by the task or event to run. Last is the period
that defines the time between successive calls of the event. This method throws exceptions that include the NullPointerException IllegalArgument
and IllegalState
Exceptions.
import java.util.Timer;
import java.util.TimerTask;
public class RepeatedTimer {
public static void main(String[] args) {
Timer timer = new Timer();
System.out.println("Stop Watch Started.");
timer.scheduleAtFixedRate(new RepeatedTask(), 500, 1000);
}
static class RepeatedTask extends TimerTask {
public void run() {
System.out.println("Running!");
}
}
}
Below is the never-ending outcome of the future event scheduled.
Running!
Running!
Running!
Running!
Rashmi is a professional Software Developer with hands on over varied tech stack. She has been working on Java, Springboot, Microservices, Typescript, MySQL, Graphql and more. She loves to spread knowledge via her writings. She is keen taking up new things and adopt in her career.
LinkedIn