How to create a timer in java?|Timers java example?

Java timer: In this tutorial, learn how to create a timer and timer task in java for example.

what are timers in java?

We have seen many scheduler programs in Linux which are based on cron jobs. Java has also a mechanism to provide the limited scheduling mechanism with the Timer and TimerTask Task.

if you want a full pledge scheduler, you can use the quartz scheduler.

Before timers classes are introduced, we have to write our own custom code for scheduler tasks using our own calculation logic using threads.

The timer can be used in real-time applications where you have a large object which wants to synch with a database for every one hour or read the logs from the apache logs and insert them into DB for every 4 hours.

Timer class implements a Runnable method which is for creating a thread. so Timer will create threads internally which cause to execute the given task at periodic intervals of time have the control for execution of multiple tasks achieves the task execution at repeated intervals or we can postpone the execution for specific intervals of time.

Timer implementation in Java can be done with the below classes

  • Timer class
  • TimerTask Class

The timer in java:-

Timer is used to specify the task execution for every interval or after the holdup of some time in an application.

Timer is java class defined in java.utilpackage

It needs TimerTask that executed the duration of the interval.

TimerTask in java:-

TimerTask is java class defined in java.util package. It implements a java.lang.runnable interface which has a run method to override. the run method of TimerTask can have code for which you want to apply the timer functionality.

This timer task can be scheduled by many times for a specific time interval duration.

How to create a Non-Dameon timer in java?

The non-Dameon timer is default timer implementation using the default constructor of Timer. Let’s see two use cases.

  • suppose you have created a timer that means threads are created internally in the background, once the run method of the thread execution is completed, the timer should not execute.
  • another case is, you have to execute the timer for 10 seconds only, after that you have to cancel the timer, the developer has the control to stop the execution of the timer(using the cancel method of the timer).

This timer causes performance effect as JVM unable to stop if the non-Dameon timer is executing . Here


Timer t=new Timer();
Timer timer=Timer(false)

How to create a Dameon timer?

Dameon timer is created in the background thread while starting and creating the timer. Dameon timer can be created using the following code

Timer timer=Timer(true);

Dameon timer is a timer that will not be stopped even your application life ends.

As the timer is completed dependent on threads, so we will see the main difference.

difference between Dameon Thread and Non-Dameon Thread?

Dameon Thread is a background thread that is created and executed in the background. the scope is JVM running time only

Non-Dameon Thread scope is an application running lifetime. Once the application is stopped, the Dameon thread stopped its execution.

These threads end when the exit method is called or run method execution is over or exception occurs.

Timer example in java:-

This is an example of How to execute timer for the repeated interval of time.

Let us see the example for the usage of timer class with printing hello world message for every one second for 10 times.

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

public class HelloMessage extends TimerTask {
 private int numberoftimes = 0;
 public void run() {
  numberoftimes++;
  if (numberoftimes <= 10) {
   System.out.println("Hello World....");
  } else {
   this.cancel();
  }
 }
}
class TimerExample {
 public static void main(String[] args) {
  Timer helloWorldTimer = new Timer();
  helloWorldTimer.scheduleAtFixedRate(new HelloMessage(), 0, 1000);
 }
}

Here is sequence of steps

  • Timer object is created
  • called the timer scheduleAtFixedRate() which has a TimerTask job that has actual code written to execute for the timer.
  • For this, we have written Custom java class HelloMessage which extends TimerTask and overrides run method execution.
  • we have used the cancel method to end the life of the timer after repeated 10 times execution.

How to Create a Countdown timer in java?

This is an Counter which prints number for every second. timer.scheduleAtFixedRate method takes TimerTask and delay=0 and period=1 Second

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

public class CounterTimer {
    public static void main(String[] args) {
        Timer timer = new Timer();

        TimerTask task = new TimerTask(){
            private int k = 0;
            public void run(){
                    System.out.println("executes function for every 1 Second"+ k);
                    k++;

            }
        };
        timer.scheduleAtFixedRate(task, 0, 1000); //1000ms = 1sec

    }
}

Hope you got enough idea on basic timers in java for your execution.

Please free to comment if you have any questions or if you liked my post.