ScheduledExecutorService在超时后结束

时间:2018-01-11 22:19:56

标签: java scheduled-tasks java-threads

美好的一天!我有调度程序,我需要检查它的工作时间。我怎样才能做到这一点?我需要在调度程序工作超过5分钟时从someFunction()返回错误

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

public int someFunction() {
    ScheduledFuture<Integer> future = 
        scheduler.schedule(new ScheduledPrinter(), 10, TimeUnit.SECONDS);
    if (scheduler.isShutdown()) {
        return future.get();
    }
}
private class ScheduledPrinter implements Callable<Integer> {
    public Integer call() throws Exception {
        // do something
        if (!serverResponse.getErrorData().equals("QueueIsNotReady")) {
            scheduler.shutdown();
            return getResponse();
        } 
        return null;
    }
}

1 个答案:

答案 0 :(得分:3)

您可以使用以下选项:

  1. scheduler.awaitTermination(5, TimeUnit.MINUTES)

    ScheduledFuture<Integer> future = 
            scheduler.schedule(new ScheduledPrinter(), 10, TimeUnit.SECONDS);
    if (!scheduler.awaitTermination(5, TimeUnit.MINUTES)) {
        throw new Exception("task did not complete");
    } 
    
  2. future.get(5, TimeUnit.MINUTES)。此方法允许您将调度程序重用于其他任务:

    ScheduledFuture<Integer> future =
            scheduler.schedule(new ScheduledPrinter(), 10, TimeUnit.SECONDS);
    future.get(5, TimeUnit.MINUTES)); // this will throw TimeoutException after 5 minutes
    
  3. 安排另一项任务在5分钟内运行,以检查第一个任务状态。此方法可用于异常处理超时。在这种情况下,someFunction会立即返回:

    ScheduledFuture<Integer> future =
            scheduler.schedule(new ScheduledPrinter(), 10, TimeUnit.SECONDS);
    scheduler.schedule(() -> {
        if (!future.isDone()) {
            future.cancel(true);  // cancel task if it runs more than 5 minutes
        }
    }, 5, TimeUnit.MINUTES);