Java Thread How to - Reinitialize fix delay in ScheduledExecutorService








Question

We would like to know how to reinitialize fix delay in ScheduledExecutorService.

Answer

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
//from   ww  w  . j a va 2 s .co m
public class Main {
  static int i = 0;
  static ScheduledExecutorService executor;
  static Runnable runnable;
  static ScheduledFuture<?> future;

  public static void main(String args[]) {
    executor = Executors.newScheduledThreadPool(1);
    runnable = new Runnable() {
      @Override
      public void run() {
        System.out.println("Inside runnable" + i++);
      }
    };
    future = executor.scheduleWithFixedDelay(runnable, 0, 2, TimeUnit.SECONDS);
    try {
      Thread.sleep(4000); // sleeping for 2 seconds
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    future.cancel(false);
    future = executor.scheduleWithFixedDelay(runnable, 0, 10, TimeUnit.SECONDS);
  }
}

The code above generates the following result.