Lasse A Karlsen
Lasse A Karlsen

Reputation: 821

Set a time limit / timeout for a method

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.

Upvotes: 5

Views: 13252

Answers (4)

yegor256
yegor256

Reputation: 105063

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.

Upvotes: 6

Jon Newmuis
Jon Newmuis

Reputation: 26502

  • If you want for it to run for two seconds, you can use Thread.sleep(2000). Note that Thread.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.

Upvotes: -3

rit
rit

Reputation: 2308

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.

Upvotes: 1

Kounavi
Kounavi

Reputation: 1121

The TimeUnit class provides method required for this.
Check it out here: TimeUnit in JDK 6

Upvotes: -1

Related Questions