Run code for x seconds in Java?

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.

Leave a Comment