Solve the problem of Task already scheduled or canceled exception when using Timer

When using java.util.Timer and java.util.TimerTask to execute scheduled tasks, if the schedule or scheduleAtFixedRate method of Timer is called, an error is reported as follows:
java.lang.IllegalStateException: Task already scheduled or canceled
indicates that the execution of the current Timer object has ended Or it is canceled. Usually, the cancel() interface of Timer or TimerTask has been executed. The current Timer and TimerTask have been consumed and cannot be used any more. If you want to continue to use, you need to recreate the object, for example:

  /**
   * 开始计时器
   */
  private void startTimer() {
    this.stopTimer();
    this.timer = new Timer();
    this.task = new TimerTask() {
        @Override
        public void run() {
            // 代码逻辑
        }
    };
    // 每隔1秒执行一次task
    this.timer.schedule(this.task, 0, 1000);
  }

  /**
   * 结束计时器
   */
  private void stopTimer() {
    if (this.timer != null) {
      this.timer.cancel();
    }
  }

Guess you like

Origin blog.csdn.net/chenzhengfeng/article/details/131991508