Java Executors run a task in an executor periodically

Introduction

The Executor framework can run periodic tasks through the ScheduledThreadPoolExecutor class.

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

class Task implements Runnable {
  private String name;

  public Task(String name) {
    this.name = name;
  }//from   ww w . jav  a  2 s. c  om

  @Override
  public void run() {
    System.out.println(name+" "+ new Date());
  }
}

public class Main {
  public static void main(String[] args) {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    System.out.println("Main: Starting at: "+ new Date());

    Task task = new Task("Task");
    ScheduledFuture<?> result = executor.scheduleAtFixedRate(task, 1, 2, TimeUnit.SECONDS);

    for (int i = 0; i < 10; i++) {
      System.out.println("Main: Delay: "+ result.getDelay(TimeUnit.MILLISECONDS));
      try {
        TimeUnit.MILLISECONDS.sleep(500);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    executor.shutdown();
    System.out.println("Main: No more tasks at: "+ new Date());
    try {
      TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("Main: Finished at: "+ new Date());
  }
}



PreviousNext

Related