Java定时器不固定延迟

发布于 2024-12-19 17:18:27 字数 632 浏览 2 评论 0原文

我需要一个基本上每 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

醉殇 2024-12-26 17:18:27

我不认为 java.util.Timer 类支持这一点。

您可以做的就是使用 Timer.schedule(TimerTask, int) 方法在一段时间后执行您的任务。当您的任务执行时,您可以使用所需的新间隔安排一个新计时器。

像这样的东西:

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)
    }
}

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:

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)
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文