具有非固定延迟的Java计时器 [英] Java timer with not-fixed delay
问题描述
我需要一个计时器
,基本上每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;
}
因此,在1000ms延迟后计时器启动并重复每个 moveTime
ms。问题是即使我将 movetime
增加1000,计时器总是以初始延迟(1000)运行,但值 movetime
每次定时器调用 run()
时,增加(2000,3000,4000等)。
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()
.
我是否遗漏了某些东西,或者我有什么选择,每隔't'秒重复一次任务,其中't'是可变的?
Am I missing something or what alternative do I have for repeating a task every 't' second with 't' being variable?
谢谢。
推荐答案
我不认为 java.util。计时器
类支持这个。
你能做的就是使用 Timer.schedule(TimerTask,int)
在一定时间后执行任务的方法。当你的任务被执行时,你可以用你想要的新间隔安排一个新的计时器。
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.
类似的东西:
int moveTime = 1000;
Timer timer = new Timer();
public Bot(){
timer.schedule(new Task(), moveTime);
}
public class Task extends TimerTask {
@Override
public void run() {
System.out.println("Time Passed from last repeat:"+movetime)
moveTime += 1000;
timer.schedule(new Task(), moveTime)
}
}
这篇关于具有非固定延迟的Java计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!