Java TimerTask 取消

标签 java timer

我遇到以下问题。每隔 2 秒,程序就会进入 if 语句。在这个 if 语句中,我想要一个计时器,它会在 15 秒后给我一条消息。计时器应延迟 1 秒运行。但是当我用计时器“等待”时,if 语句将再执行 7 次。我的问题是,我总是有 7 个相同的 TimerTask 同时运行。我怎么解决这个问题?

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);
}

最佳答案

来自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.

这意味着您可以立即运行任务,每秒执行一次

关于Java TimerTask 取消,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38831736/

相关文章:

java - "safe"语言的安全漏洞

java - postman REST 客户端原始 json 数据如何在 POST、PUT 调用中发送到服务器?

java - Eclipse CDT 扩展以构建附加语言

Python:启动和停止计时器

C# 定时器回调在每个循环中使用函数的返回值

Java构造函数在不同类中的使用

java - hibernate延迟初始化异常

android - 在警报对话框中显示倒数计时器

ios - NSTimer timerWithTimeInterval : not working

vb.net - 如何创建运行时 timer.tick 事件?