Run code for x seconds in Java?

Danny King picture Danny King · Jan 8, 2010 · Viewed 71.5k times · Source

I'd like to write a java while loop that will iterate for 15 seconds. One way I thought to do this would be to store the current system time + 15sec and then compare that to the current time in the while loop signature.

Is there a better way?

Answer

Nick Fortescue picture Nick Fortescue · Jan 8, 2010

The design of this depends on what you want doing for 15s. The two most plausible cases are "do this every X for 15s" or "wait for X to happen or 15s whichever comes sooner", which will lead to very different code.

Just waiting

Thread.sleep(15000)

This doesn't iterate, but if you want to do nothing for 15s is much more efficient (it wastes less CPU on doing nothing).

Repeat some code for 15s

If you really want to loop for 15s then your solution is fine, as long as your code doesn't take too long. Something like:

long t= System.currentTimeMillis();
long end = t+15000;
while(System.currentTimeMillis() < end) {
  // do something
  // pause to avoid churning
  Thread.sleep( xxx );
}

Wait for 15s or some other condition

If you want your code to be interrupted after exactly 15s whatever it is doing you'll need a multi-threaded solution. Look at java.util.concurrent for lots of useful objects. Most methods which lock (like wait() ) have a timeout argument. A semaphore might do exactly what you need.