Skip to main content

How to create/ schedule a Job or Thread to run at fixed intervals

Points To Remember


  • TimerTask is a class that can run a Thread repeatedly after a specific period.
  • You can either implement your own class also by implementing Runnable Interface.
    • Then you may need to put your thread to sleep and then resume the thread after a desired interval.
The TimerTask will do this more efficiently for you then implementing your own code.

How to schedule a Thread to run after fixed interval

We will be using TimerTask to schedule the Thread after every 1 sec.

TimerTask class in Java implements Runnable interface and has the following methods.

  • cancel - to cancel the timer task when needed.
  • scheduledExecutionTime - gives the time when the task was last executed successfully.
  • run - an abstract method that needs to be implemented.

MyTask.java

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

class MyTask extends TimerTask {

static int count = 0;

@Override
public void run(){
if(count < 5){
System.out.println(" MyTask called ### count = "+ (++count));
}
else {
cancel();
System.out.println("######### TASK CANCELLED #######");
}
}

}


TestTimerTask.java

import java.util.TimerTask;
import java.util.Timer;

class TestTimerTask {

public static void main(String args[]){

TimerTask task = new MyTask();
Timer timer = new Timer();
timer.scheduleAtFixedRate(task,0,1000);

}

}

 MyTask called  ### count = 1
 MyTask called  ### count = 2
 MyTask called  ### count = 3
 MyTask called  ### count = 4
 MyTask called  ### count = 5
#########    TASK CANCELLED    #######

So Thread goes on executing till it is stopped manually or till cancel() is called on the task.

Comments