我試圖創建一個方法,可以在最長的時間內執行給定的任務。如果在這段時間內沒有完成,在放棄之前應重試多次。它也應該在每次嘗試之間等待幾秒鐘。這是我提出的,我想對我的方法提出一些批評。他們是使用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;
}