Friday, August 28, 2009

Scheduling Task for specific time usinng TimerTask and Timer in Java

Java  Utils package provides class called Timer which is facility for threads to schedule task for future execution. Execution can be one time or repeated.

To Schedule Specific task using Time, You need to do Following
1. Create TimerTask
2. Create Object of Timer
3. Schedule timer using timer.schedule


Java Program to create Own TimeTask

package com.anuj.utils.timer;

import java.util.Date;
import java.util.TimerTask;

public class MyTimerTask extends TimerTask {

 Date date;
 
 @Override
 public void run() {
  date = new Date();
  System.out.println("This one is Executed at : "+date);
 }

}

Java Program to schedule TimerTask using Timer.schedule :


package com.anuj.utils.timer;

import java.util.Timer;

public class TimerDemo {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Timer timer = new Timer();
  MyTimerTask myTimerTask = new MyTimerTask();
  
  timer.schedule(myTimerTask, 0,1000);

  for(int i=0;i<=10;i++){
   try {
    System.out.println("Execution in Main Thread : "+i);
    Thread.sleep(1000);
    if(i==10){
     System.exit(0);
    }
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }

}

No comments:

Post a Comment