java 为方法设置时间限制/超时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7678121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set a time limit / timeout for a method
提问by Lasse A Karlsen
I have a simple method like this:
我有一个像这样的简单方法:
public void foo(int runForHowLong) {
Motor.A.forward();
}
Now a want to be able to pass an argument to foo(), which sets a time limit for how long foo() will run. Like if I send foo(2), it runs for 2 seconds.
现在希望能够将参数传递给 foo(),它设置了 foo() 运行多长时间的时间限制。就像我发送 foo(2) 一样,它会运行 2 秒。
回答by yegor256
You can use AOP and a @Timeable
annotation from jcabi-aspects(I'm a developer):
您可以使用 AOP 和@Timeable
来自jcabi-aspects的注释(我是开发人员):
class Motor {
@Timeable(limit = 1, unit = TimeUnit.SECONDS)
void forward() {
// execution as usual
}
}
When time limit is reached your thread will get interrupted()
flag set to true
and it's your job to handle this situation correctly and to stop execution.
当达到时间限制时,您的线程将被interrupted()
设置为标志,true
您的工作是正确处理这种情况并停止执行。
回答by rit
Look at this question on Stackoverflow: Run code for x seconds in Java?
看看 Stackoverflow 上的这个问题:Run code for x seconds in Java?
It is exactly the same related to the requirements.
它与要求完全相同。
As I interprete from your question you'd like to have the method running for 2 minutes. To achieve that you need to start a Thread which you control for 2 minutes and then stop the thread.
正如我从您的问题中解释的那样,您希望该方法运行 2 分钟。为此,您需要启动一个您控制 2 分钟的线程,然后停止该线程。
回答by Kounavi
The TimeUnit
class provides method required for this.
Check it out here: TimeUnit in JDK 6
的TimeUnit
类提供此要求的方法。
在这里查看:JDK 6 中的 TimeUnit
回答by Jon Newmuis
If you want for it to run for two seconds, you can use
Thread.sleep(2000)
. Note thatThread.sleep(2000)
is more of a "suggestion" than a "command"; it will not run for exactly2000 milliseconds, due to scheduling in the JVM. It can pretty much be simplified to be roughly2000 milliseconds.If you want it to continue calling
forward
for 2 seconds (which would result in quite a few invocations of the function), you will need to use a timer of some sort.
如果你想让它运行两秒钟,你可以使用
Thread.sleep(2000)
. 请注意,这Thread.sleep(2000)
更像是“建议”而不是“命令”;它不会运行恰好2000毫秒,由于JVM调度。它几乎可以简化为大约2000 毫秒。如果您希望它继续调用
forward
2 秒(这将导致该函数多次调用),您将需要使用某种计时器。