Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run code for x seconds in Java?

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?

like image 742
Danny King Avatar asked Jan 08 '10 16:01

Danny King


People also ask

How do you repeat a code in Java?

The Do/While Loop This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

How do you make a program stop for a few seconds in Java?

The easiest way to delay a java program is by using Thread. sleep() method. The sleep() method is present in the Thread class. It simply pauses the current thread to sleep for a specific time.

How do you call a function repeatedly after a fixed time interval in Java?

The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed. 1 second = 1000 milliseconds.


1 Answers

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.

like image 116
Nick Fortescue Avatar answered Sep 18 '22 09:09

Nick Fortescue