我有一个代码
for (int i = 0; i < 10000 i++) {
//call every 1000ms
Thread.sleep(1000);
doLongTimeOperation();
}
长时间运行
void doLongTimeOperation(){
//Long time op
Thread.sleep(randomInt);
}
我需要每隔固定的时间段(1000)调用这个方法。 IE,如果方法在 500ms 内执行,则下一次调用应该在 500ms 之后(500+500=1000)。如果方法在 2000ms 内执行,则下一次调用应该在 0ms 之后。如何实现?谢谢
最佳答案
最好的选择是 ScheduledExecutorService.scheduleWithFixedDelay 方法。
scheduleWithFixedDelay(可运行命令,长初始延迟,长延迟,TimeUnit 单位):
"Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next."
有关更多详细信息,请查看此链接:
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html#scheduleWithFixedDelay(java.lang.Runnable ,长,长,java.util.concurrent.TimeUnit)
没有计算任何事情的紧张:)。请注意它与 ScheduleAtFixedRate 方法不同。希望对您有所帮助。
关于java - 如何在给定执行时间的情况下每隔固定时间调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22600449/