Java Executors run a task in an executor after a delay

Introduction

The Executor framework ThreadPoolExecutor class can execute Callable and Runnable tasks with a pool of threads.

To execute a task after a period of time or to execute a task periodically, use the ScheduledThreadPoolExecutor class.


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

class Task implements Callable<String> {
  private String name;

  public Task(String name) {
    this.name = name;
  }//from   ww w  .java2  s . co  m
  @Override
  public String call() throws Exception {
    System.out.println(name+" "+ new Date());
    return "Hello, world";
  }
}
public class Main {
  public static void main(String[] args) {
    ScheduledExecutorService executor = (ScheduledExecutorService) Executors.newScheduledThreadPool(1);
    System.out.println("Main: Starting at: "+ new Date());
    for (int i = 0; i < 5; i++) {
      Task task = new Task("Task " + i);
      executor.schedule(task, i + 1, TimeUnit.SECONDS);
    }
    executor.shutdown();
    try {
      executor.awaitTermination(1, TimeUnit.DAYS);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("Core: Ends at: "+ new Date());
  }
}



PreviousNext

Related