java - 定时器任务在第一次运行后停止调用运行方法
问题描述
我是编程新手,我正在做一个 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()
方法吗?
解决方案
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()
推荐阅读
- java - 将 nbt 数据转换为 itemstack - Spigot
- javascript - 如何使用用户提交的代码,并获取其错误以获取相关信息?
- c++ - PX4 在 z 轴上旋转低 yaw_rate
- python - 如何使用 typer lib 捕获 CLI 选项的多个值?
- r - 如何检查是否已经使用 R 中的 extrafont 包加载了给定的字体?
- streaming - 流数据的高可用性节点断开连接
- python - 如何从 DGL 的数据集中可视化图表?
- reactjs - 为什么点击提交后我的输入仍然存在?
- php - 在 MYSQL 中存储邮政编码列表的正确方法是什么?
- javascript - observable - 如何使用 forEach 和 setTimeout 返回值?(与 Rxjs 无关)