3fbf1b6b3cd0c1c4380311af0b0198877b836510
[JavaForFun] /
1 package de.test.thread.executor.future;
2
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;
9
10
11 public class TimerSchedulerExample {
12         ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
13
14         public void test() {
15                 ScheduledFuture<Integer> future = executor.schedule(new Callable<Integer>() {
16
17                         @Override
18                         public Integer call() throws Exception {
19                                 return 666;
20                         }
21
22                 }, 2000, TimeUnit.MILLISECONDS);
23
24                 long delay;
25                 while ((delay = future.getDelay(TimeUnit.MILLISECONDS)) > 0) {
26                         System.out.println("Delay: " + delay);
27                 }
28
29                 try {
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);
36                 } finally {
37                         future.cancel(true);
38                 }
39         }
40         
41         
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;
48         else
49             throw new IllegalStateException("Not unchecked", exception);
50     }
51 }