Core Java

Java Timer Class Example

In this article, we shall discuss the Java Timer Class and some of its important methods with an example.

1. What is Java timer?

A timer is a facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.

java class timer example

Corresponding to each Timer object is a single background thread that is used to execute all of the timer’s tasks, sequentially. The timer’s task execution thread terminates gracefully after all the outstanding tasks have completed execution. The timer’s task execution thread can be terminated by calling the timer’s cancel method.

The class is thread-safe and hence multiple threads can share a single Timer object without the need for external synchronization.

2. Constructors in Timer

Let us now look at the constructors in Timer class – java.util.Timer.

  • Timer() – Creates a new timer. The associated thread does not run as a daemon.
  • public Timer(String name) – Creates a new timer whose associated thread has the specified name. The associated thread does not run as a daemon.
  • public Timer(boolean isDaemon) – Creates a new timer whose associated thread may be specified to run as a daemon. A daemon thread is needed when the timer is used to schedule repeatable maintenance activities that must be performed as long as the application is running, but without prolonging the lifetime of the application.
  • public Timer(String name, boolean isDaemon) – Creates a new timer whose thread has the specified name and can be specified to run as a daemon.

3. Methods in Timer

Let us now look at some methods of Timer class

  • public void schedule(TimerTask task, long delay) – Schedules the specified task for execution after the specified delay
  • public void schedule(TimerTask task, Date time) – Schedules the specified task for execution at the specified time. If the time is in the past, the task is scheduled for immediate execution.
  • public void schedule(TimerTask task, long delay, long period) – Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period
  • public void schedule(TimerTask task, Date firstTime, long period) – Schedules the specified task for repeated fixed-delay execution, beginning at the specified time. Subsequent executions take place at approximately regular intervals, separated by the specified period
  • public void scheduleAtFixedRate(TimerTask task, long delay, long period) – Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period
  • public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) – Schedules the specified task for repeated fixed-rate execution, beginning at the specified time. Subsequent executions take place at approximately regular intervals, separated by the specified period
  • public void cancel() – Terminates the timer without interfering with a currently executing task, if one exists. The execution thread terminates gracefully and no more tasks can be scheduled on it.
  • public int purge() – Removes all the canceled tasks from this timer’s task queue. Calling this method has no effect on the behavior of the timer but eliminates the references to the canceled tasks from the queue. If there are no external references to these tasks, they become eligible for garbage collection.

4. Java Timer Class Example

Let us now look at an example to check the usage of the Timer class. MyTask is a task that will be scheduled or run by the Timer class. The task could be any event or application behavior like retrieving data from host systems or triggering a batch job. Let us give a time delay of 3 seconds as a placeholder for such a task.

MyTask.java

import java.util.TimerTask;
import java.util.Date;

public class MyTask extends TimerTask{
    public void run(){
        System.out.println("Begin my task for thread : "+Thread.currentThread().getName()+" at :"+new Date());
        try{
            Thread.sleep(3000L);
        } catch(InterruptedException e){
            e.printStackTrace();
        }
        
        System.out.println("Finish my task for thread :"+Thread.currentThread().getName()+" at :"+new Date());
        
    }
}

The next class is our main class that schedules this task either once or repetitively at regular periods of time. Note the usage of schedule(TimerTask task, long delay) method for timer instance. The task is executed once and then the timer is canceled. In the next scenario, note the usage of scheduleAtFixedRate(TimerTask task, long delay, long period) for timer2 object. The task in this case is executed repeatedly for a period of 3 seconds. The first task begins after a delay of 1 second and the timer is canceled after 10 seconds. The final executing task exits gracefully after completion.

TimerTest.java

import java.util.TimerTask;
import java.util.Timer;
import java.util.Date;

public class TimerTest{
    public static void main(String args[]){
        TimerTask task = new MyTask();
        // usage of constructor public Timer(String name)
        Timer timer = new Timer("Timer#1");
        System.out.println("Schedule timer with 1 sec delay at :"+new Date());
        // usage of method schedule(TimerTask task, long delay)
        timer.schedule(task,1000L);
        // provide a time delay for the task to complete
        try{
            Thread.sleep(5000L);
        } catch(InterruptedException e){
            e.printStackTrace();
        }
        System.out.println("Canceling Timer#1");
        // usage of method cancel
        timer.cancel();
        System.out.println("Cancelled Timer#1");
        
        // create another timer to demonstrate usage of scheduleAtFixedRate method
        Timer timer2 = new Timer("Timer#2");
        TimerTask task2 = new MyTask();
        System.out.println("Schedule timer#2 after a delay of 1 sec and 3 second period");
        // usage of method scheduleAtFixedRate(TimerTask task, long delay, long period)
        timer2.scheduleAtFixedRate(task2,1000L,3000L);
        System.out.println("Schedule timer#2 job done");
        // provide a time delay for the task to complete
        try{
            Thread.sleep(10000L);
        } catch(InterruptedException e){
            e.printStackTrace();
        }
        
        System.out.println("Canceling Timer#2");
        // usage of method cancel
        timer2.cancel();
        System.out.println("Cancelled Timer#2");
        
    }
}

Executing the class would give output as shown below

Schedule timer with 1 sec delay at :Thu Feb 20 15:22:36 IST 2020
Begin my task for thread : Timer#1 at :Thu Feb 20 15:22:37 IST 2020
Finish my task for thread :Timer#1 at :Thu Feb 20 15:22:40 IST 2020
Canceling Timer#1
Cancelled Timer#1
Schedule timer#2 after a delay of 1 sec and 3 second period
Schedule timer#2 job done
Begin my task for thread : Timer#2 at :Thu Feb 20 15:22:42 IST 2020
Finish my task for thread :Timer#2 at :Thu Feb 20 15:22:45 IST 2020
Begin my task for thread : Timer#2 at :Thu Feb 20 15:22:45 IST 2020
Finish my task for thread :Timer#2 at :Thu Feb 20 15:22:48 IST 2020
Begin my task for thread : Timer#2 at :Thu Feb 20 15:22:48 IST 2020
Canceling Timer#2
Cancelled Timer#2
Finish my task for thread :Timer#2 at :Thu Feb 20 15:22:51 IST 2020

5. Download the Source Code

Download
You can download the full source code of this example here: Java Timer Class Example

Venkat-Raman Nagarajan

Venkat works for a major IT firm in India and has more than a decade of experience working and managing Java projects for a banking client.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Bill Fly
Bill Fly
4 years ago

Parts of your article are difficult to read because they are light and smaller type.

Back to top button