我想每隔5秒执行一次位于for循环中的特定代码。
我该怎么做呢?
发布于 2020-03-14 19:30:19
在这种情况下,java.util.Timer将是更合适的解决方案。计时器允许您每隔x毫秒执行一次函数。不过,您必须在循环之外定义和调用计时器。
或者,您可以查看@Filburt建议的link,在其中您可以使用当前时间每隔x秒执行一次循环中的代码。
如果你仍然想使用定时器解决方案,下面是如何设置它的:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run () {
// code to execute
}
}, MILLISECONDS); // replace MILLISECONDS with the amount of milliseconds between each execution.请注意,计时器本身并不知道何时停止。您可以在匿名类中创建一个字段,用于对每次执行进行计数,并在达到特定数字时取消计时器:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
int times = 0;
@Override
public void run () {
if (times == 5) { // replace 5 with the amount of times you want the code executed.
timer.cancel();
return;
}
// code to execute
times++;
}
}, MILLISECONDS);https://stackoverflow.com/questions/60681469
复制相似问题