Java定时器不固定延迟
我需要一个基本上每 t 秒执行一次操作的 Timer
。但我希望能够修改计时器重复任务的计时器周期。我写了这样的内容:
public Bot() {
timer = new Timer();
timer.schedule(new Task(), 1000, moveTime = 1000);
}
public class Task extends TimerTask {
@Override
public void run() {
System.out.println("Time Passed from last repeat:" + movetime)
moveTime += 1000;
}
因此,在 1000 毫秒延迟后,计时器启动并每 moveTime
毫秒重复一次。问题是,即使我将 movetime 增加 1000,计时器始终以初始延迟(1000)运行,但 movetime 的值每次都会增加(2000,3000,4000 等)计时器调用 run()
的时间。
我是否遗漏了某些内容,或者我有什么替代方案可以在“t”可变的情况下每隔“t”秒重复一次任务?
谢谢。
I need a Timer
that basicaly does something every t seconds. But I want to be able to modify the timer period at which the timer repeats the task. I wrote something like this:
public Bot() {
timer = new Timer();
timer.schedule(new Task(), 1000, moveTime = 1000);
}
public class Task extends TimerTask {
@Override
public void run() {
System.out.println("Time Passed from last repeat:" + movetime)
moveTime += 1000;
}
So, After 1000ms delay the timer starts and repeats every moveTime
ms. The problem is even if I increased movetime
by 1000, the timer always runs at initial delay(1000) but the value of movetime
increases(2000,3000,4000 etc) each time the timer calls run()
.
Am I missing something or what alternative do I have for repeating a task every 't' second with 't' being variable?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不认为 java.util.Timer 类支持这一点。
您可以做的就是使用 Timer.schedule(TimerTask, int) 方法在一段时间后执行您的任务。当您的任务执行时,您可以使用所需的新间隔安排一个新计时器。
像这样的东西:
I don't think that the
java.util.Timer
class supports this.Something you can do is use the
Timer.schedule(TimerTask, int)
method that executes your task one after a certain amount of time. When your task gets executed, you can then scheduled a new timer with the new interval you want.Something like: