如何在 Java 中使用 while 循环停止计时器 (util)?

How to stop a Timer (util) with a while loop in Java?

描述: 我试图在 i=10 时用 while 循环从 运行 停止计时器。这只是一个测试。在我的项目中,我实际上打算使用计时器从在线数据库中检查一个布尔值,并在返回“true”后停止计时器。

代码:


public static void main(String[] args) {
    Timer timer = new Timer();

    TimerTask task = new TimerTask() {
        int i = 0;

        @Override
        public void run() {
            System.out.println("Timer ran for:" + ++i);
        }
    };

    while (i < 10) {
        timer.schedule(task, 0, 1000);
    }
}

输出:

Timer ran for:1
Exception in thread "main" java.lang.IllegalStateException: Task already scheduled or cancelled
    at java.base/java.util.Timer.sched(Timer.java:402)
    at java.base/java.util.Timer.schedule(Timer.java:249)
    at Code.testUtilTimer.main(testUtilTimer.java:31)
Timer ran for:2
Timer ran for:3
Timer ran for:4
Timer ran for:5
Timer ran for:6
Timer ran for:7
Timer ran for:8
Timer ran for:9
Timer ran for:10
Timer ran for:11

我认为您不需要使用 while 循环。已经计划将在特定时间间隔工作。如果你按照我的例子去做,你就会解决你的问题。

 TimerTask task = new TimerTask() {
        public void run() {
            boolean dbValue = //Database operations
            if(dbValue) {
              cancel();
            }
           
        }
    };
    Timer timer = new Timer("Timer");
    
    timer.scheduleAtFixedRate(task, 1000L, 1000L);

您正在创建多个时间调度程序,这就是异常的原因。

您应该创建一次计划任务(运行 每 X 次)然后等待。

public static void main(String[] args) {
    Timer timer = new Timer();

    TimerTask task = new TimerTask() {
        int i = 0;

        @SneakyThrows
        @Override
        public void run() {
            if (++i > 5) {
                timer.cancel(); // no more times
            } else {
                Thread.sleep(1000);
                System.out.println("Timer ran for:" + i);
            }
        }
    };

    timer.schedule(task, 0, 500);

    System.out.println("waiting for all tasks completion...");
}

有输出

waiting for all tasks completion...
Timer ran for:1
Timer ran for:2
Timer ran for:3
Timer ran for:4
Timer ran for:5

Process finished with exit code 0