我是编程新手,我正在做一个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);TimerTask:
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()方法吗?
发布于 2020-12-23 08:31:34
您可以使用可以通过scheduleAtFixedRate以固定速率调度Timer任务,
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()
发布于 2020-12-22 16:27:54
这条线
timer.schedule(connectivityTimerTask,30 * 1000)在延迟30秒后运行任务,一旦任务完成,计时器的工作也就完成了。
如果要定期运行任务,还必须指定间隔时间段
schedule (TimerTask task, long delay, long period) // "period" specifies how often you want to run the task请阅读文档here。
发布于 2020-12-23 07:26:51
要在一段时间后重复运行某些代码,请使用带有Handler的Runnable,如下所示
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
// do your logging
handler.postDelayed(this, 30000);
}
};
handler.post(runnable); // or handler.postDelayed(runnable, 30000) if you want it to wait 30s before starting initially取消
handler.removeCallbacks(runnable);https://stackoverflow.com/questions/65405061
复制相似问题