如何解决如何在 Java 中为进程实现超时?
我想为一个进程实现超时,如果它花费的时间超过 X 秒,我希望它停止并执行 return 语句,无论如何。 在我的实际使用中,我会调用 REST API,apiCallController() 代表控制器。
根据我在下面的尝试,一切都会继续执行。
我该如何解决这个问题?
编辑:如果我要实现的目标有效,则长时间运行的任务将无法完成,这意味着该行
#Option 1 ---> with your example you dint need an __init__
class budget:
def __init__(self,money):
self.money = money
class food(budget):
def show(self):
print('hi')
money = 50
a = food(money)
a.show()
#Option 2 if you still need to override the init
class budget:
def __init__(self,money):
print('here')
self.money = money
class food(budget):
def __init__(self,money):
super().__init__(money)
def show(self):
print('hi')
money = 50
a = food(money)
a.show()
永远不会打印,还有这一行
System.out.println("End http/SSH stuff...");
也不会被执行,将响应变量保留为初始初始化
response = "Call successful...";
但我还是需要在超时后返回响应
我一直在这个 Java fiddle 中进行测试(你可以直接粘贴代码):https://javafiddle.leaningtech.com/
谢谢。
String response = "Call aborted...";
编辑 2:从接受的答案中,我只是重构了一点:
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;
}
}
解决方法
您的任务在打印到控制台后已完成,但您的计时器正在等待更多任务,因此仍在运行,并且由于它仍在运行,main
函数不会退出。
如果您没有其他任务,则需要cancel
您的计时器。
try
{
Timer timer = new Timer();
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)");
}
},timeoutSeconds * 1000
);
System.out.println("Start http/SSH stuff...");
Thread.sleep(longRunningTaskDurationSeconds * 1000);
System.out.println("End http/SSH stuff...");
response = "Call successful...";
timer.cancel();
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("\npasta...");
return "\n" + response;
编辑
由于问题已根据实际用例进行了更新,因此我在此处添加了一个编辑以建议该用例的答案(之前的部分可能与现在的问题无关)。
这是我对你的问题的解决方案,看看。我已经使用 Future
和 ScheduledExecutorService
来实现它。
public static String apiCallController() {
System.out.println("creepy...\n");
String response = "Call aborted...";
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
Callable<String> r = () -> {
try {
// To mimick the actual call
TimeUnit.SECONDS.sleep(5);
System.out.println("call successful...");
return "Some response";
} catch (InterruptedException e) {
System.out.println("Timeout reached,aborting... (This is where I want everything to stop without killing JVM/Tomcat)");
throw e;
}
};
Future<String> task = executor.submit(r);
try
{
System.out.println("Start http/SSH stuff...");
//Let's just wait for 3 secs for response to arrive
response = task.get(3,TimeUnit.SECONDS);
System.out.println("End http/SSH stuff...");
response = "Call successful...";
}
catch(InterruptedException | TimeoutException e)
{
// cancelling a task,either it was interrupted (sleep call can be interrupted) or its timeout
task.cancel(true);
}catch (ExecutionException e) {
//Something went wrong horribly
e.printStackTrace();
}
System.out.println("\npasta...");
// 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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。