gpt4 book ai didi

java - 定时器预定无法在它发生之前找出如何停止它

转载 作者:行者123 更新时间:2023-11-29 03:22:19 24 4
gpt4 key购买 nike

好吧,我似乎无法让预定的计时器停止/取消 :( 如果有人知道如何请帮助我 :D

/*Here follows the code */

private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Timer timer = new Timer();
if (jToggleButton1.isSelected()) {
jToggleButton1.setText("STOP");
jToggleButton1.setBackground(Color.red);
System.out.println("is called");
timer.schedule(new TimerTask() {
@Override
public void run() {
// Your database code here
System.out.println("scheduled time reached");
}
}, times * 1000);
} else {
jToggleButton1.setText("START");
jToggleButton1.setBackground(Color.green);
set = false;
System.out.println("i called it");
timer.cancel(); //?????this doesnt seem to work :(
}
}

最佳答案

你说:

The problem is what you just mentioned about the timer, i want to stop the current tasks that are running

根据 java.util.Timer API,在 Timer 对象上调用 cancel() 会阻止它创建新的 future 任务,但不会停止当前正在运行的任务任务。因此,由于这是您的问题,cancel() 对您没有帮助也就不足为奇了。

解决方案?这在于您正在创建的 TimerTasks。如果这是我的代码,我会创建一个扩展 TimerTask 的类,它有一个干净的方法来停止它,也许给它一个 cancel() 方法,保留这些 Activity 运行实例的集合,然后在需要时调用 cancel()

警告,在 Swing 应用程序中不小心使用 java.util.Timer 可能很危险。如果您的任务涉及进行 Swing 调用,则需要注意在 Swing 事件线程上进行 Swing 调用。如果不是,并且所有的任务都是数据库操作,那么您就可以了。

顺便说一句,如果你使用 ScheduledExecutorService ,您可以用 Runnables 或 Callables 填充它。 schedule(...)scheduleAtFixedRate(...) 方法返回一个您可以调用 cancel() 的 ScheduledFuture。我认为这可以通过在任务上调用 Thread.interrupt() 来实现。因此,如果您走这条路,您的任务应该是可中断的,并且应该能够顺利处理 InterruptedException

关于java - 定时器预定无法在它发生之前找出如何停止它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22887254/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com