Wednesday, July 1, 2009

Task Scheduling in Java


In Java, the Timer class helps you to schedule tasks to run at some time in the future. The tasks can be run either once or repeatedly like a batch job. 


Tasks can be scheduled to run in the following way:

  • Create Timers using a simple constructor of the Timer class. This creates a Timer Thread.
  • Subclass the TaskTimer class to represent your task. Implement the run() method and put your task implementation details here.
  • Schedule the task using one of the schedule() methods of the Timer class.


Types of Schedule

There are 3 types of schedules:

  • One time schedule

This runs the task once after the delay time specified. Here is an example:



import java.util.Timer;

import java.util.TimerTask;


public class MyTimer {

public static void main(String[] args) {

Timer timer = new Timer();

TimerTask task = new TimerTask() {

public void run() {

System.out.println("Scheduled Task");

}

};

//Execute this task after 0 milliseconds i.e. immediately

timer.schedule(task,0);

}


}

  • Fixed-delay schedule

This runs the task repeatedly after the initial delay time specified. The time between the subsequent executions is specified by a period time. This schedule ensures that the period time elapses between invocations. Here is one example:


long oneday = 24*60*60*1000;

//Execute this task every day starting immediately. Make sure

//that there is a 24 hr delay between the invocations. So if the

//last invocation was delayed for some reason, the delay carries

//forward.

timer.schedule(task, 0, oneday);


  • Fixed-rate schedule


This runs the task repeatedly after the initial delay time specified. The time between the subsequent executions is specified by a period time. This schedule ensures that the task runs during their scheduled time .i.e it is not affected by the time of its previous invocation. Example:

//Way to setup a cron or batch job. Make sure that the task 

//runs at the fixed time every 24 hrs. If the last invocation

//was delayed due to some reason, the delay is not reflected in the

//next invocation.

timer.scheduleAtFixedRate(task,0,oneday);


Some interesting facts:

  • Each Timer object runs only one background thread. So if multiple tasks are assigned to the same Timer object, they will be run sequentially. To run them in parallel you have to create multiple Timer objects. 
  • The class is thread-safe.
  • There is no mechanism to cancel the currently executing task. There is a cancel method which terminates the Timer thread and thereby discards any scheduled tasks but does not affect the currently executing task.


No comments:

Post a Comment