简体   繁体   中英

Java TimerTask cancel

I have the following problem. Every 2 seconds the programm will go inside an if statement. Inside this if statement I want to have a timer that will give me a message after 15 seconds. The timer should be run with a delay of 1 second. But while I'm "waiting" with the timer, the if statement will be executed another 7 times. My problem is, I have always 7 same TimerTask at the same time running. How can I solve this problem?

if (response == true) {
  final Timer timer = new Timer(); 
  final int keepAliveTimeout = 15000; //15 seconds
  timer.schedule(new TimerTask() {
    @Override
    public void run() {
      if (response) {
        response = false;
        Log.i(TAG, "********Response******");
        timeoutCounter = 0;
      } else if (timeoutCounter > keepAliveTimeout) {
        Log.i(TAG, "********Timer Timeout******");
      }

      Log.i(TAG, "********Timer******");
      timeoutCounter = timeoutCounter + 1000;
    }
  }, 0, 1000);
}

From Java API :

public void schedule(TimerTask task, long delay, long period)

Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.

which means you run your task without delay, to be executed every second

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM