重启计时器失败

时间:2012-10-30 12:31:23

标签: java timertask

我想在收到KeepAlive时重启我的计时器,问题是有时它不会重新启动,而不是它会创建一个新计时器,所以,最后计时器达到了限制:

public class KeepAliveTimer {


long macAddress;
Timer timer;
String ip;  


public KeepAliveTimer(long mac, String ipAddress){
    this.macAddress = mac;
    this.ip = ipAddress;

    timer = new Timer();

    TimerTask timerTask = new TimerTask() {

        @Override
        public void run() {

            timerFinished();

        }
    };

    timer.schedule(timerTask, 10*60*1000);
}


public void update() {


    TimerTask timerTask = new TimerTask() {

        @Override
        public void run() {
            timerFinished();

        }
    };
    timer.cancel();
    timer.purge();
    timer = new Timer();
    timer.schedule(timerTask, 10*60*1000);
}

public void timerFinished() {

    //tasks
}

}

当收到第一个keepAlive并通过以下

更新时,会创建对象KeepAliveTimer

1 个答案:

答案 0 :(得分:1)

您不应该取消整个计时器,而只取消TimerTask。这就是我编写代码的方式:

public class KeepAliveTimer {
  final Timer timer = new Timer();
  final long macAddress;
  final String ip;
  volatile TimerTask timerTask;

  public KeepAliveTimer(long mac, String ipAddress) {
    this.macAddress = mac;
    this.ip = ipAddress;
  }
  public void update() {
    if (timerTask != null) timerTask.cancel();
    timer.schedule(timerTask(), 10 * 60 * 1000);
  }
  private TimerTask timerTask() {
    return timerTask = new TimerTask() {
      @Override public void run() { timerFinished(); }
    };
  }
  public void timerFinished() {
    // tasks
  }
}

请注意,我不会在构造函数中复制调度。你应该用

初始化
new KeepAliveTimer(mac, ip).update();