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
  • 195,986
  • 40
  • 382
  • 396
Lasse A Karlsen
  • 771
  • 5
  • 13
  • 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
  • 97,508
  • 114
  • 426
  • 573
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,288
  • 3
  • 18
  • 26
-1

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

Kounavi
  • 1,061
  • 1
  • 13
  • 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
  • 24,486
  • 2
  • 47
  • 56