Ad

Thursday 8 August 2013

Timer and TimerTask in Java- An Example

In the last Post,we saw the description about each of the schedule method provided by the Timer API.
Lets start with a sample program to demonstrate how the Timer can can be used to schedule the task.

Let say our task(Job)  is to display the Current Time and need to be scheduled to run at different time.We need to write a Task for this-MyTimerTask and that should extend the Class TimerTask .The implementation(ie displaying the current Time) of the Task  has to be written in the run method.Then the task can be scheduled to run by using any of the schedule method of the Timer API depending on our requirement.

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimerExample {

public static void main(String[] args) {

    TimerExample timerExample= new TimerExample();
    timerExample.scheduleTimerTask();
     /*Have an Infinite while loop,so that the main program wont be terminated */
    while (true)
    {
   
    }
}

public  void scheduleTimerTask()
{
Timer timer= new Timer();
MyTimerTask timerTask=null;
Calendar calendar= Calendar.getInstance();
calendar.set(Calendar.HOUR,10);
calendar.set(Calendar.MINUTE,00);
calendar.set(Calendar.SECOND,00);
System.out.println("calendar"+calendar.getTime());

/*To Schedule the task to run once after 5 seconds*/
timerTask= new MyTimerTask("Type1");
timer.schedule(timerTask,5*1000); //

/*To Schedule the task to run once at Current Date 10:00 AM*/
timerTask= new MyTimerTask("Type2");
 timer.schedule(timerTask,calendar.getTime());

  /*Fixed Delay Execution-To Schedule the task to run repeatedly with specified
   interval of 5 seconds.First Time execution of the Task will start after 10 seconds*/
 timerTask= new MyTimerTask("Type3");
timer.schedule(timerTask,10*1000,5*1000);

/*Fixed Delay Execution-To Schedule the task to run repeatedly with specified
interval of 5 seconds.First Time execution of the Task will start at current Date 10:00 AM*/
timerTask= new MyTimerTask("Type4");
timer.schedule(timerTask,calendar.getTime(),5*1000);

/*Fixed Rate Execution-To Schedule the task to run repeatedly with specified
interval of 5 seconds.First Time execution of the Task will start at current Date 10:00 AM*/
timerTask= new MyTimerTask("Type5");
timer.scheduleAtFixedRate(timerTask,calendar.getTime(),5*1000);

/*Fixed Rate Execution-To Schedule the task to run repeatedly with specified
 interval of 5 seconds.First Time execution of the Task will start after 10 seconds*/
timerTask= new MyTimerTask("Type6");
timer.scheduleAtFixedRate(timerTask,10*1000,5*1000);
}

}

class MyTimerTask extends TimerTask
{

private String scheduleType="";
public MyTimerTask(String scheduleType)
{
this.scheduleType=scheduleType;
}

@Override
public void run() {
System.out.println("Job of Scheduled Type:"+scheduleType+" Is executed at Time:"+new Date());
}

}

Related Topics:

2 comments: