Tuesday, February 1, 2011

Job Scheduling in Java

How to Schedule a Job or Task in Java

To schedule a job to occur at a certain time or to be excuted at repeated time interval
we can use TimerTask and Timer class in java to accomplish 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

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.



package com.vels.test;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* @author velmurugan pousel
* @project test
* created on Feb 1, 2011
*/
public class EmailTask extends TimerTask {

/**
* method will be called at every scheduled time(ex ..1 minute)
*/
public void run() {
System.out.println(" start to send mail...." + new Date());
sendMail();
System.out.println(" after mail sent...." +
System.currentTimeMillis());
}

public void sendMail() {
System.out.println(" email send.....");
}

public static void main(String[] args) {

int DELAY = 60*1000; // one minute delay

Timer t1 = new Timer();
t1.schedule(new EmailTask(),DELAY, DELAY);
//calls the run method to send mail after one minute and
repeat every one minute.

// task - task to be scheduled.
// delay - delay in milliseconds before task is to be
executed.
// period - time in milliseconds between successive task
executions.
}
}


To cancel the Scheduled task we need to call cancel method of the TimerTask( we can override the cancel method).

2 comments:

  1. i want to excute the task on every day 3 pam,.,,,

    ReplyDelete