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 Runable 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”.

 

Advertisements

One thought on “How to schedule a job in Java?

  1. backgrounds for facebook free January 5, 2013 at 5:36 am Reply

    Great post. I was checking continuously this blog and
    I am impressed! Extremely useful info particularly the last part 🙂 I care for such information a lot.
    I was looking for this particular info for a long time.
    Thank you and good luck.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: