Scheduling in Java

Some Java applications need some task to run every regular interval of time. For eg. Sending bank account statement to account holders every month via email or generating EOD(End of Day) report daily in the evening.

In Java this is done using java.util.TimerTask and java.util.Timer

This 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.

Corresponding to each Timer object is a single background thread that is used to execute all of the timer’s tasks, sequentially. Timer tasks should complete quickly. If a timer task takes excessive time to complete, it “hogs” the timer’s task execution thread. This can, in turn, delay the execution of subsequent tasks, which may “bunch up” and execute in rapid succession when (and if) the offending task finally completes.

After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer’s task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can take arbitrarily long to occur. By default, the task execution thread does not run as a daemon thread, so it is capable of keeping an application from terminating. If a caller wants to terminate a timer’s task execution thread rapidly, the caller should invoke the timer’s cancel method.

If the timer’s task execution thread terminates unexpectedly, for example, because its stop method is invoked, any further attempt to schedule a task on the timer will result in an IllegalStateException, as if the timer’s cancel method had been invoked.

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

This class does not offer real-time guarantees: it schedules tasks using the Object.wait(long) method.

This class can scale to large numbers of concurrently scheduled tasks (thousands should present no problem). Internally, it uses a binary heap to represent its task queue, so the cost to schedule a task is O(log n), where n is the number of concurrently scheduled tasks.

import java.util.TimerTask;
import java.util.Date;
/**
 * 
 * @author Bharat Sharma
 */
// Create a class extends TimerTask
public class ScheduledTask extends TimerTask {

	Date currentTime; // to display current time

	// Add your code or logic here
	public void run() {
		currentTime = new Date(); // initialize date
		System.out.println("Time is :" + currentTime); // Display current time
	}
}

The steps to scheduling of above task are as below.

  1. Create an instance of Timer class Timer timer = new Timer();
  2. Create an instance of ScheduledTask class ScheduledTask task = new ScheduledTask();
  3. Assign ScheduledTask to Timer timer.schedule(task);
import java.util.Timer;
/**
 * 
 * @author Bharat Sharma
 */
//Main class
public class SchedulerMain {
	public static void main(String args[]) throws InterruptedException {

		Timer timer = new Timer(); // Step 1 - Instantiate Timer Object
		ScheduledTask st = new ScheduledTask(); // Step 2 - Instantiate SheduledTask class
		timer.schedule(st, 0, 1000); // Step 3 - Create Repetitively task for every 1 secs
	}
}

References:
Java Documentation

, , , , ,

  1. JavaPins

Leave a comment