gpt4 book ai didi

java - 如何在Java中的方法中设置超时并在一段时间内重试方法

转载 作者:行者123 更新时间:2023-11-30 07:41:12 27 4
gpt4 key购买 nike

我编写了一个 java 方法,它连接到 Web 服务。有时这种方法需要很长时间才能建立连接。我想要例如它需要超过 5 秒,然后停止当前程序并重新启动 3 次以上。如果所有时间都失败,则完全中止。

到目前为止,我已经写了以下内容:

        private ConnectionInterface  connectWithTimeout() throws MalformedURLException, Exception {

ExecutorService executor = Executors.newCachedThreadPool();
Callable<Object> task = new Callable<Object>() {
public Object call() throws InterruptedException, MalformedURLException, Exception {
return connectWithNoTimeout(); //This is the method that takes to long. If this method takes more than 5 seconds, I want to cancel and retry for 3 more times. Then abort completely.
}
};
Future<Object> future = executor.submit(task);
try {
Object result = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException ex) {

System.out.println( "Timeout Occured");

} catch (InterruptedException e) {
System.out.println( " "InterruptedException Occured");


} catch (ExecutionException e) {
System.out.println( ""ExecutionException Occured");


} finally {

future.cancel(true); // here the method gets canceled. How do I retry it?
}
System.out.println( "Connected !!");
return connectWithNoTimeout();
}



private ConnectionInterface connectWithNoTimeout() throws MalformedURLException, Exception {}

最佳答案

您的方法已经有 5 秒超时。您现在需要做的就是添加某种具有 3 次重复的循环。您需要超时计数器和成功尝试后的休息时间。不确定发生其他异常时您想做什么,也在那里添加了中断。以下代码应该可以完成这项工作:

private ConnectionInterface  connectWithTimeout() throws MalformedURLException, Exception {
int repeatCount = 0;

ExecutorService executor = Executors.newCachedThreadPool();
Callable<Object> task = new Callable<Object>() {
public Object call() throws InterruptedException, MalformedURLException, Exception {
return connectWithNoTimeout(); //This is the method that takes to long. If this method takes more than 5 seconds, I want to cancel and retry for 3 more times. Then abort completely.
}
};

while (repeatCount < 3){
Future<Object> future = executor.submit(task);
try {
Object result = future.get(5, TimeUnit.SECONDS);
break;

} catch (TimeoutException ex) {
repeatCount++;
System.out.println( "Timeout Occured");

} catch (InterruptedException e) {
System.out.println( " "InterruptedException Occured");
break;

} catch (ExecutionException e) {
System.out.println( "ExecutionException Occured");
break;

} finally {

future.cancel(true); // here the method gets canceled. How do I retry it?
}
}
System.out.println( "Connected !!");
return connectWithNoTimeout();
}

关于java - 如何在Java中的方法中设置超时并在一段时间内重试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56234349/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com