TimerTask start stop 只执行一次
问题是,我只能执行一次计时器。我知道它是因为我调用了函数timer2.cancel();和timer1.cancel(); :: 取消“不再运行这个”。我需要一个替换功能,该功能实际上会停止计时器,但在我重新安排计时器时可以再次启动。我该如何去做呢?
public void actionPerformed (ActionEvent e){
if (e.getSource()==jbtStart)
{
System.out.println("Start is pressed");
timer2.cancel();
timer1.schedule(new Task(), 0, delay);
}
else if (e.getSource()==jbtStop)
{
System.out.println("Stop is pressed");
timer1.cancel();
timer2.schedule(new Task2(), 0, delay);
}
Problem, I can only execute my timer once. I know its because I called the function timer2.cancel(); and timer1.cancel(); :: Cancel being "Never run this ever again". I need a replacement function, one that actually stops a timer, but can be started back up again when I reschedule it. How do I go about doing that?
public void actionPerformed (ActionEvent e){
if (e.getSource()==jbtStart)
{
System.out.println("Start is pressed");
timer2.cancel();
timer1.schedule(new Task(), 0, delay);
}
else if (e.getSource()==jbtStop)
{
System.out.println("Stop is pressed");
timer1.cancel();
timer2.schedule(new Task2(), 0, delay);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不在此时创建一个新的
Timer
呢?或者,或者保留 TimerTask 和计时器,并取消该任务而不是计时器本身。作为第三种可能的替代方案,有一个计时器任务和一个计时器,但要让计时器任务知道它在任何时候要做什么 - 看起来您正在有效地切换您想要的内容每次计时器滴答作响时执行的操作。您始终可以保留两个单独的类来分离逻辑功能,然后有一个“包装器”任务,它允许您替换每次运行时执行的行为。
Why not just create a new
Timer
at that point? Either that, or keep hold of theTimerTask
as well as the timer, and cancel that instead of the timer itself.As a third possible alternative, have a single timer task and a single timer, but make the timer task aware of what it's meant to do at any point - it looks like you're effectively toggling what you want to do each time the timer ticks. You could always keep two separate classes to separate the logical functionality, and then have a "wrapper" task which allows you to replace what behaviour is executed on each run.
我会取消 TimerTasks 而不是计时器(并且我只会使用一个计时器)。
更新:
I would cancel the TimerTasks instead of the Timers (and I would use only one Timer).
UPDATE: