我是编程新手,我正在做一个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()
https://stackoverflow.com/questions/65405061
复制相似问题