Runs a task with given time budget.
(Runnable task, long seconds)
| 113 | * Runs a task with given time budget. |
| 114 | */ |
| 115 | public static void runWithTimeout(Runnable task, long seconds) { |
| 116 | Duration timeout = Duration.ofSeconds(seconds); |
| 117 | ExecutorService executor = Executors.newSingleThreadExecutor(); |
| 118 | Future<?> handler = executor.submit(task); |
| 119 | try { |
| 120 | handler.get(timeout.getSeconds(), TimeUnit.SECONDS); |
| 121 | } catch (TimeoutException e) { |
| 122 | e.printStackTrace(); |
| 123 | System.exit(1); |
| 124 | } catch (InterruptedException | ExecutionException e) { |
| 125 | e.printStackTrace(); |
| 126 | } finally { |
| 127 | executor.shutdown(); |
| 128 | } |
| 129 | } |
| 130 | } |