开发者

running loop for 5 minutes

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


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:

  1. The current loop iteration will always complete, so in practice it will always run for a bit more than 5 minutes.
  2. For this application System.nanoTime() is more suitable than System.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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜