Showing posts with label scheduling. Show all posts
Showing posts with label scheduling. Show all posts

Friday, August 24, 2007

Time Scheduling in Java

Some Applications need to execute certain jobs and tasks at an exactly a perticular time or at regular time intervals. Let us see how to schedule the tasks to achieve that functionality, for this purpose java provides a standerd API Timer in java.util package, Now we will see how Java developers can implement such a requirement using the standard Java Timer API.

A Sample Code To use Timer:

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

public class Remainder {
Timer timer;

public Remainder ( int seconds ) {
timer = new Timer ( ) ;
timer.schedule ( new TimerTask(){
public void run ( ) {
System.out.println ( "Your scheduled Task Starts...." ) ;
timer.cancel ( ) ; //Terminate the Timer after task completion
}
} , seconds*1000 ) ;
}

public static void main (String args[]){
System.out.println ( "Before schedule task." ) ;
new Remainder ( 5 ) ;
System.out.println ( "Task scheduled." ) ;
}
}