ScheduledExecutorService in Java


Java Multithreading ScheduledExecutorServiceViews 3393

ScheduledExecutorService

The ScheduledExecutorService interface in Java is a concurrency utility that is a subinterface of the ExecutorService. This interface is present in the java.util.concurrent package. Whenever we want to schedule a task or execute tasks periodically or after a fixed time period, we can use the ScheduledExecutorService interface. It is similar to a Timer task but this interface is useful in a multithreading environment.

public interface ScheduledExecutorService extends ExecutorService

Hierarchy

ScheduledExecutorService in Java

ScheduledThreadPoolExecutor is the class that implements the ScheduledExecutorService interface. This interface is a child interface of the ExecutorService interface that extends the Executor interface.

Methods

Below are the methods of the ScheduledExecutorService interface.

MethodDescription
ScheduledFuture schedule(Callable c, long delay, TimeUnit timeunit)Submits a value returning task after a fixed delay
ScheduledFuture schedule(Runnable command, long delay, TimeUnit timeunit)Submits a one-shot task that enables after a fixed delay
ScheduledFuture scheduleAtFixedRate(RUnnable command, long initialDelay, long period, TimeUnit timeunit)Submits a periodic action that enables after the intial delay and executes periodically at fixed timeperiod
ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit timeunit)Submits a periodic action after the inital delay and then continues periodically after the specific delay time period.

Example: schedule(Callable) using Java ScheduledExecutorService

The below example schedules a task using the Callable command after a delay of 3 seconds. Using the get() method of the ScheduledFuture object, we can retrieve the result of the call() method.

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorServiceDemo {

  public static void main(String[] args) throws InterruptedException, ExecutionException {
    ScheduledExecutorService se = Executors.newScheduledThreadPool(5);
    ScheduledFuture sf = se.schedule(new Callable() {

      public Object call() throws Exception {
        System.out.println("Schedule using Callable command");
        return "Done";
      }
      
    }, 3, TimeUnit.SECONDS);
    
    System.out.println("Result of ScheduledFuture: " + sf.get());
    se.shutdown();
  }

}
Schedule using Callable command
Result of ScheduledFuture: Done

Example: schedule(Runnable) using Java ScheduledExecutorService

This is an example of scheduling a task by passing the Runnable command using the Java ScheduledExecutorService interface. It invokes the run() method after a delay of 3 seconds.

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorServiceDemo {

  public static void main(String[] args) throws InterruptedException, ExecutionException {
    ScheduledExecutorService se = Executors.newScheduledThreadPool(5);
    System.out.println("Start Execution");
    
    ScheduledFuture sf = se.schedule(new Runnable() {

      public void run() {
        System.out.println("Schedule using Runnable command");
      }
      
    }, 3, TimeUnit.SECONDS);
    
    se.shutdown();
  }

}
Start Execution
Schedule using Runnable command

Example: scheduleAtFixedRate using ScheduledExecutorService

We can also schedule a task at periodic time intervals using the scheduleAtFixedRate method of the Java ScheduleExecutorService interface. This method executes the task after a specific delay and then executes repeatedly at a specified time interval. In the below example, it schedules the printText task for every 2 seconds after an initial delay of 3 seconds until the scheduler runs for 10 seconds. After 10 seconds, it cancels the task and shuts down the ScheduledExecutorService. This method executes until it calls the cancel method that cancels the task.

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ScheduleAtFixedRateDemo {

  public static void main(String[] args) {
    ScheduledExecutorService se = Executors.newScheduledThreadPool(1);
    ScheduledFuture sf = se.scheduleAtFixedRate(new printText(), 3, 2, TimeUnit.SECONDS);
    
    se.schedule(new Runnable() {

      public void run() {
        sf.cancel(true);
        se.shutdown();
        System.out.println("Shutting down...");
      }
      
    }, 10, TimeUnit.SECONDS);
  }
  
}

class printText implements Runnable {
  public void run() {
    System.out.println("Schedule");
  }
}
Schedule
Schedule
Schedule
Schedule
Shutting down...

Example: scheduleWithFixedDelay using Java ScheduledExecutorService

We can also schedule a task with a fixed delay by using the scheduleWithFixedDelay method of the Java ScheduledExecutorService interface. The below example demonstrates the same. This method executes until it calls the cancel method that cancels the task.

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ScheduleAtFixedRateDemo {

  public static void main(String[] args) {
    ScheduledExecutorService se = Executors.newScheduledThreadPool(1);
    ScheduledFuture sf = se.scheduleWithFixedDelay(new displayTime(), 3, 2, TimeUnit.SECONDS);
    se.schedule(new Runnable() {

      public void run() {
        sf.cancel(true);
        se.shutdown();
        System.out.println("Shutting down...");
      }
      
    }, 10, TimeUnit.SECONDS);
  }
  
}

class displayTime implements Runnable {
  public void run() {
    System.out.println("Schedule at: " + new Date());
  }
}
Schedule at: Sat Mar 27 15:29:00 IST 2021
Schedule at: Sat Mar 27 15:29:02 IST 2021
Schedule at: Sat Mar 27 15:29:04 IST 2021
Schedule at: Sat Mar 27 15:29:06 IST 2021
Shutting down...

 

Reference

Translate ยป