Set a time limit / timeout for a method
I have a simple method like th开发者_开发技巧is:
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.
You can use AOP and a @Timeable
annotation from jcabi-aspects (I'm a developer):
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.
Look at this question on 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.
The TimeUnit
class provides method required for this.
Check it out here: TimeUnit in JDK 6
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 exactly 2000 milliseconds, due to scheduling in the JVM. It can pretty much be simplified to be roughly 2000 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.
精彩评论