views:

778

answers:

3

I'm looking for functionality in java identical to this in ruby:

SystemTimer.timeout_after(30.seconds) do do something end

i could achieve this by forking a thread and then killing it after a while, but is there a simpler way?

A: 

Either run it in a Thread or do something like that:

void method() {
    long endTimeMillis = System.currentTimeMillis() + 10000;
    while (true) {
     // method logic
     if (System.currentTimeMillis() > endTimeMillis) {
      // do some clean-up
      return;
     }
    }
}

As you can see, this doesnt work for all kind of methods.

Mork0075
+2  A: 

Cant you just use the Java Timer?

A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.

willcodejavaforfood
A: 

You can create a ThreadPoolExecutor, which has an invokeAll method who recievs a timeout as a parameter.

David Rabinowitz