Showing posts with label TimerTask. Show all posts
Showing posts with label TimerTask. Show all posts

Sunday, March 13, 2011

How to schedule a job in Java?

When there is a need for schedule an event to occur at a certain time, or the event needs to be executed repeated at a certain interval, the TimerTask and TImer class are designed for this.

A TimerTask is  “A task that can be scheduled for one-time or repeated execution by a Timer.” A TimerTask is similar to a Thread. Both classes implement the Runnable interface.  Thus both classes need to implement the public void run() method. The code inside the run() method is will be executed by a thread. The TimerTask has two more methods besides the run() method. They are the public boolean cancel() and the public long scheduledExecutionTime(). The cancel() method cancels the not yet executed task. The scheduledExecautionTime() returns the most recent actual execution time of this task.

A Timer is facility to schedule TimerTasks. "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."  The constructor of the Timer class starts the background thread.

An simple example here:
public class SimpleTimer {

    class Checker extends TimerTask {
        public static final int DELAY = 60 * 1000;
    
        public void run() {

            doCheck();

        }


        private void doCheck() {
            System.out.println("Current time is: " + System.currentTimeMillis());
        }
    }

    pubic static void main (String … argv) {

        Timer timer = new Timer(); // start the timer thread
        timer.schedule(Checker(), Checker.DELAY,
                Checker.DELAY); // calls the Checker's run() method after one minute and repeat every one minute.
    }
}
For a gracefully shutdown, the Timer's cancel() method should be called. The cancel() method "Terminates this timer, discarding any currently scheduled tasks".

Chitika