【发布时间】:2021-07-03 20:38:57
【问题描述】:
我想为一个进程实现超时,如果它需要超过 X 秒,我希望它停止并执行 return 语句。 在我的实际使用中,我会调用一个 REST API,apiCallController() 代表控制器。
根据我在下面尝试的所有内容,无论如何都会继续执行。
我该如何解决这个问题?
编辑:如果我想要实现的工作,长时间运行的任务将无法完成,这意味着该行
System.out.println("End http/SSH stuff...");
永远不会打印,而这一行
response = "Call successful...";
也不会执行,将响应变量保留为最初初始化的状态
String response = "Call aborted...";
但我仍然需要在超时后返回响应
我一直在这个 Java fiddle 中进行测试(你可以直接粘贴代码):https://javafiddle.leaningtech.com/
谢谢。
import java.util.*;
import java.lang.*;
public class JavaFiddle
{
public static void main(String[] args)
{
String response = apiCallController();
System.out.println(response);
}
public static String apiCallController() {
System.out.println("creepy...\n");
int timeoutSeconds = 2;
int longRunningTaskDurationSeconds = 5;
String response = "Call aborted...";
try
{
new Timer().schedule(
new TimerTask() {
@Override
public void run() {
System.out.println("Timeout reached, aborting... (This is where I want everything to stop without killing JVM/Tomcat)");
// System.exit(0); This guy shut tomcat down x_X
return;
}
},
timeoutSeconds * 1000
);
System.out.println("Start http/SSH stuff...");
Thread.sleep(longRunningTaskDurationSeconds * 1000);
System.out.println("End http/SSH stuff...");
response = "Call successful...";
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("\npasta...");
return "\n" + response;
}
}
编辑 2:根据接受的答案,我只是重构了一点:
import java.util.*;
import java.lang.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.ExecutionException;
public class JavaFiddle
{
public static void main(String[] args)
{
System.out.println("creepy...\n\n");
String response = apiCallController();
System.out.println(response);
System.out.println("\n\npasta...");
}
public static String apiCallController() {
String response = "Stuff TIMED out...";
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
Callable<String> r = () -> {
try {
System.out.println("Start http/SSH stuff...");
TimeUnit.SECONDS.sleep(5);
System.out.println("End http/SSH stuff...");
return "Stuff COMPLETED successfully...";
} catch (InterruptedException e) {
throw e;
}
};
Future<String> task = executor.submit(r);
try {
response = task.get(3, TimeUnit.SECONDS);
} catch(InterruptedException | TimeoutException e) {
task.cancel(true);
} catch (ExecutionException e) {
e.printStackTrace();
}
// Need to shutdown executor (think of it is master thread here)
// You may want to control this behaviour outside of this function call
executor.shutdown();
return "\n" + response;
}
}
【问题讨论】:
-
timeout*1000是什么? -
我正在将秒转换为毫秒。
-
对了,你可以把
timeoutSeconds * 1000换成更明显的Duration.ofSeconds( timeoutSeconds ).toMillis()。更好的是,将timeoutSeconds的类型更改为名为timeout的Duration对象。
标签: java multithreading timer timeout