TimerTask start stop only executing once
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);
      }
Why not just create a new Timer at that point? Either that, or keep hold of the TimerTask 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.
I would cancel the TimerTasks instead of the Timers (and I would use only one Timer).
UPDATE:
   private Task task1;
   private Task2 task2;
 public void actionPerformed (ActionEvent e){
      if (e.getSource()==jbtStart)
      {
          System.out.println("Start is pressed");
          if (task2 != null) {
              task2.cancel();
          }
          task1 = new Task();
          timer.schedule(task1, 0, delay);
      }
      else if (e.getSource()==jbtStop)
      {   
            System.out.println("Stop is pressed");
            if (task1 != null) {
                task1.cancel();
            }
            task2 = new Task2();
            timer.schedule(task2, 0, delay);
      }
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论