Pages Navigation Menu

Coding is much easier than you think

Scheduling a time delay and execute periodically in Java

 
A simple timer schedule can be used to create a time delay in your java program. You can make use of the class Timer from java.util package. Timer is capable of scheduling an initial time delay after which the task starts executing AND the time gap for the consecutive execution of the same tasks.

 

The syntax for the time schedule can be understood as

timer.schedule(,,);
Note : The time gaps are in milli Seconds

Below is a simple java program that makes use of timer to schedule an initial and consecutive time delays for a particular task.

package com.simpleCodeStuffs.timer;

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

public class TimerWithInitialDelay {
public static void main(String args[]){
	 Timer timer = new Timer();
	 int initialDelay=5;
	 int consecutiveDelays=2;
	 final Calendar cal=Calendar.getInstance();
	 System.out.println("SimpleCodeStuffs!!! START "+cal.getTime()+"\\n");
	 
     timer.schedule(new TimerTask() {
          public void run() {
        	  Calendar currentTime=Calendar.getInstance();
        	  System.out.println("SimpleCodeStuffs!!! TASK   "+currentTime.getTime());
              }
          }, (initialDelay*1000), consecutiveDelays * 1000);
}
}

On running this program, the output appears as :-
 

timer delay

 

Notice in the output that, there is a time gap of 5 seconds from the commencement of the program to the execution of the task. After the initial execution, there is a time gap of 2 seconds between every consecutive execution of the tasks.
 

dwd2
Download It -€“TimerSchedule