5

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
Lasse A Karlsen
  • 801
  • 5
  • 14
  • 23

4 Answers4

6

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.

yegor256
  • 102,010
  • 123
  • 446
  • 597
1

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.

Community
  • 1
  • 1
rit
  • 2,308
  • 3
  • 19
  • 27
-1

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

Kounavi
  • 1,090
  • 1
  • 12
  • 24
-3
  • 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.

Jon Newmuis
  • 25,722
  • 2
  • 45
  • 57