首页 > 解决方案 > 定时器任务在第一次运行后停止调用运行方法

问题描述

我是编程新手,我正在做一个 android 应用程序,我有一个要求,我需要监控 30 年代的一些日志。我正在使用计时器任务,但是发生了什么,如果 30 秒结束并且 run 方法在它终止后执行,则计时器任务不会重复。

这是我的代码:

connectivityTimerTask = new ConnectivityTimerTask();
timer = new Timer(true);
//timer = new Timer(); // tried with this but it is not working
timer.schedule(connectivityTimerTask,30 * 1000);

定时器任务:

public class ConnectivityTimerTask extends TimerTask {

        @Override
        public void run() {
            Log.error("----- ACK NotReceived -----" + System.currentTimeMillis());
            //resetMonitor(); using this method I am setting the timer again
        }
    }

我想知道安排重复时间的最佳做法是什么。我使用正确的方法吗?我可以使用该resetMonitor()方法吗?

标签: javaandroidtimertimertask

解决方案


schedule()您可以使用可以以固定速率安排的Timer任务,而不是scheduleAtFixedRate,

int THIRTY_SECONDS = 30 * 1000;
Timer mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        // do whatever you want every 30s
        Log.e("TAG", "----- ACK NotReceived -----" + System.currentTimeMillis());
    }
}, 0, THIRTY_SECONDS);

每当您想停止计时器调用时timer.cancel()


推荐阅读