1 package de.test.thread.executor.future;
3 import java.util.concurrent.Callable;
4 import java.util.concurrent.ExecutionException;
5 import java.util.concurrent.Executors;
6 import java.util.concurrent.ScheduledExecutorService;
7 import java.util.concurrent.ScheduledFuture;
8 import java.util.concurrent.TimeUnit;
11 public class TimerSchedulerExample {
12 ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
15 ScheduledFuture<Integer> future = executor.schedule(new Callable<Integer>() {
18 public Integer call() throws Exception {
22 }, 2000, TimeUnit.MILLISECONDS);
25 while ((delay = future.getDelay(TimeUnit.MILLISECONDS)) > 0) {
26 System.out.println("Delay: " + delay);
30 Integer result = future.get();
31 System.out.println(result);
32 } catch (InterruptedException e) {
33 Thread.currentThread().interrupt();
34 } catch (ExecutionException e) {
35 throw launderThrowable(e);
42 private RuntimeException launderThrowable(final Throwable exception) {
43 exception.printStackTrace();
44 if (exception instanceof RuntimeException)
45 return (RuntimeException) exception;
46 else if (exception instanceof Error)
47 throw (Error) exception;
49 throw new IllegalStateException("Not unchecked", exception);