java 运行循环 5 分钟
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3768258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
running loop for 5 minutes
提问by sjain
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
我需要在 5 分钟内运行一段时间循环。我寻找了计时器 api,但我找不到这样做。任何人都可以为此提供代码片段。
谢谢
回答by sleske
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.
这将运行循环,直到超过 5 分钟过去。
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.
- 当前循环迭代将始终完成,因此在实践中它始终会运行 5 分钟多一点。
- 对于此应用程序
System.nanoTime()
更合适,System.currentTimeMillis()
因为如果调整计算机的系统时钟,后者会发生变化,从而中断计算。感谢 Shloim 指出这一点。
回答by Shloim
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).
此循环将运行 5 分钟。它不会受到对计算机日期/时间所做的更改(由用户或 NTP)影响。
long endTime = System.nanoTicks() + TimeUnit.NANOSECONDS.convert(5L, TimeUnit.MINUTES);
while ( System.nanoTicks() < endTime ){
// do whatever
}
Other methods like System.currentTimeMillis()
should be avoided, because they rely on the computer date/time.
System.currentTimeMillis()
应该避免使用其他方法,因为它们依赖于计算机日期/时间。
回答by Waldheinz
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.
因为您在谈论计时器 API,所以我猜您所追求的是延迟而不是“循环运行 5 分钟”。如果是这种情况,您可以使用Thread.sleep(..) 之类的东西,它可以让 CPU 做更多有用的事情,而不是忙着等待。或者至少节省一些能源和地球。