运行循环5分钟 [英] running loop for 5 minutes

查看:111
本文介绍了运行循环5分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求在5分钟内运行一个while循环。
我找了计时器api,但我找不到这样做。
任何人都可以为此提供代码snipet。


谢谢

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
}

这将运行循环,直到超过5分钟。

This will run the loop, until more than 5 minutes have elapsed.

注意:


  1. 当前循环迭代将始终完成,因此在实践中它将始终运行超过5分钟。

  2. 对于此应用程序 System.nanoTime() System.currentTimeMillis()更合适,因为后者将如果计算机的系统时钟被调整,则更改,从而放弃计算。 感谢Shloim指出这一点。

  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.

这篇关于运行循环5分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆