I have a requirment to run a while loop the 5 min.
I looked for the timer api but I could not found to do this.
Can any one provide a code snipet for this.
Thanks
Asked
Active
Viewed 1.8k times
3 Answers
12
The easiest way will be to just check how much time has elapsed on each iteration. Example:
final long NANOSEC_PER_SEC = 1000l*1000*1000;
long startTime = System.nanoTime();
while ((System.nanoTime()-startTime)< 5*60*NANOSEC_PER_SEC){
// do stuff
}
This will run the loop, until more than 5 minutes have elapsed.
Notes:
- The current loop iteration will always complete, so in practice it will always run for a bit more than 5 minutes.
- For this application
System.nanoTime()
is more suitable thanSystem.currentTimeMillis()
because the latter will change if the computer's system clock is adjusted, thus throwing off the calculation. Thanks to Shloim for pointing this out.

sleske
- 81,358
- 34
- 189
- 227
-
2If the user adjusts his clock while your loop is running, then your loop will not run for 1 minute. It might run for months or years. That's because `System.currentTimeMillis()` returns the amount of msecs since 1970/01/01-00:00:00. You need a time counter that is monotone, like `System.nanoTicks()` – Shloim Jan 12 '16 at 12:36
-
Here is a clean solution without using system clock. https://stackoverflow.com/a/71611647/3190214 – katwekibs Mar 25 '22 at 02:57
5
This loop will run for 5 minutes. It will not be effected by changes made to the computer's date/time (either by user or by NTP).
long endTime = System.nanoTime() + TimeUnit.NANOSECONDS.convert(5L, TimeUnit.MINUTES);
while ( System.nanoTime() < endTime ){
// do whatever
}
Other methods like System.currentTimeMillis()
should be avoided, because they rely on the computer date/time.

Dave Jarvis
- 30,436
- 41
- 178
- 315

Shloim
- 5,281
- 21
- 36
1
Because you are talking about the timer API I guess what you are after is a delay instead of a "loop running for 5min". If this is the case you could use something like Thread.sleep(..) which would allow to let the CPU do more usefull stuff that busy-waiting. Or at least save some energy and the planet.

Waldheinz
- 10,399
- 3
- 31
- 61
-
Yes, for a simple delay this is the right answer. The question is a bit unclear... – sleske Sep 23 '10 at 21:52