我试图创建一个方法,可以在最长的时间内执行给定的任务。如果在这段时间内没有完成,在放弃之前应重试多次。它也应该在每次尝试之间等待几秒钟。这是我提出的,我想对我的方法提出一些批评。他们是使用ScheduledExecutorService
来做到这一点的更简单的方法,还是我这样做的方式就够了吗?Java执行任务时执行了多次重试和超时
public static <T> T execute(Callable<T> task, int tries, int waitTimeSeconds, int timeout)
throws InterruptedException, TimeoutException, Exception {
Exception lastThrown = null;
for (int i = 0; i < tries; i++) {
try {
final Future<T> future = new FutureTask<T>(task);
return future.get(timeout, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
lastThrown = ex;
} catch (ExecutionException ex) {
lastThrown = (Exception) ex.getCause();
}
Thread.sleep(TimeUnit.SECONDS.toMillis(waitTimeSeconds));
}
if (lastThrown == null) {
lastThrown = new TimeoutException("Reached max tries without being caused by some exception. " + task.getClass());
}
throw lastThrown;
}