How to do a task repeatedly using threads in java / How to create a timer using ScheduledThreadPoolExecutor in java

Suppose we want to do a task after fixed time interval such as creating a beep sound after 5 seconds or checking the connection status after every 5 seconds. This may be easily accomplished using Executor framework in java.
There is a class called ScheduledThreadPoolExecutor which has the methods to perform such kind of scheduling. Let’s get down to code right away:

public static void beepAfterInterval() {
//initialize the scheduler service
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
//schedule a task to execute after every 5 seconds
final ScheduledFuture<?>beeper = scheduler.scheduleAtFixedRate(new Runnable() {
   @Override
   public void run() {
   // this is just a sample. Any repeatitive task such as connection
                        // health monitoring can be done here
    System.out.println("Beep");
    
   }
  }, 0, 5, TimeUnit.SECONDS);
 }
 /*
* The above piece of code is sufficient to create a scheduler. Now suppose, if 
* we want to stop the scheduler after a definite time, say 10 minutes then 
* below piece of code will do that 
*/
  ses.schedule (new Runnable() {
   @Override
   public void run() {
    beeper.cancel(true);
    ses.shutdown();
   }
  }, 10, TimeUnit.SECONDS);

Let’s tweak in:

1. First create an instance of ScheduledThreadPoolExecutor class using newScheduledThreadPool method of Executors class. This method takes a number which defines the size of thread pool to create.
2. This is assigned to a reference of type ScheduledExecutorService since the signature of newScheduledThreadPool returns an object of type ScheduledExecutorService while internally it returns an instance of type ScheduledThreadPoolExecutor.
3. Now using this reference we call scheduleAtFixedRate method. This method takes 4 arguments:
a. A runnable object which defines the task to execute.
b. An initialDelay which defines the time after which the supplied task will start to execute the first time.
c. Period which defines the time interval after which the task will repeat itself.
d. Unit of the time interval such as minutes, seconds etc.
4. This method is declared in ScheduledExecutorService while implemented in ScheduledThreadPoolExecutor. Remember, ScheduledExecutorService is an interface while ScheduledThreadPoolExecutor is a class which implements ScheduledExecutorService. Quite confusing names :).
5. If an execution takes longer than the time interval for the next task to begin (5 seconds in this case), then the subsequent task will wait for the previous task to end.
6. If an execution of a task raises an exception, then all subsequent tasks are stopped.
7. schedule method executes a particular action after the specified time only once. This method is also declared in ScheduledExecutorService while implemented in ScheduledThreadPoolExecutor similar to scheduleAtFixedRate method and takes the task to execute, time after which to execute and the time unit.

Leave a Reply