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 ExecutorTest9 { public ExecutorTest9() { ScheduledExecutorService e = Executors.newScheduledThreadPool(10); ScheduledFuture future = e.scheduleAtFixedRate(new RunnableTask("Task AT Fixed Rate"), 2000, 2000, TimeUnit.MILLISECONDS); System.out.println("Task is called at " + new Date()); try { Thread.sleep(10000L); } catch (InterruptedException ex) {} future.cancel(true); try { Thread.sleep(2000L); } catch (InterruptedException ex) {} future = e.scheduleWithFixedDelay(new RunnableTask("Task WITH Fixed Delay"), 2000, 2000, TimeUnit.MILLISECONDS); System.out.println("Task is called at " + new Date()); try { Thread.sleep(10000L); } catch (InterruptedException ex) {} future.cancel(true); e.shutdown(); } class RunnableTask implements Runnable { private String name; public RunnableTask(String name) { this.name = name; } public void run() { System.out.println(name + " starts at " + new Date()); try { Thread.sleep(1000L); } catch (InterruptedException ex) { System.out.println(name + " is Canceled"); return; } System.out.println(name + " is done at " + new Date()); } } public static void main(String[] args) { new ExecutorTest9(); } }