0

当我收到 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
}

}

对象 KeepAliveTimer 在收到第一个 keepAlive 时创建并由后续更新

4

1 回答 1

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();
于 2012-10-30T12:40:35.740 回答