如果该方法中有异常,如何在stopTask()方法中设置CompletableFuture完成或失败操作? 我有一些代码:
private static class SenderTask implements Runnable {
private final Sender sender;
private ScheduledFuture<?> task;
@Override
public void run() {
try {
LOGGER.debug("SenderTask {} calling.", sender.getName());
sender.process();
} catch (Exception e) {
LOGGER.error(e);
}
}
public CompletableFuture<SenderTask> stopTask() {
return CompletableFuture.supplyAsync(() -> {
task.cancel(false);
LOGGER.info("Sender {} try stopping.", sender.getName());
try {
task.get(sender.getSenderConfig().getTimeoutConfig().getSendFileTimeout(),` TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
LOGGER.error(e);
}
return this;
});
}
}
我需要知道任务何时停止。
答案 0 :(得分:0)
可以使用这样的句柄:
public CompletableFuture<SenderTask> stopTask() {
return CompletableFuture.supplyAsync(() -> {
task.cancel(false);
LOGGER.info("Sender {} try stopping.", sender.getName()); task.get(sender.getSenderConfig().getTimeoutConfig().getSendFileTimeout(),TimeUnit.MILLISECONDS);
return this;
}).handle((res, ex) -> {
if(ex != null) {
LOGGER.error(ex);
...
}
return res;
});
}