java - 在应用程序进入后台时暂停 scheduleAtFixedRate Timer?
问题描述
这是我的固定速率计时器代码。我可以在活动进行时暂停此计时器吗onPause();
?如果是这样,那么您建议我在onPause();
方法和计时器中添加什么,应该在应用程序出现时开始工作onResume();
:
//Declare the timer
t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// code here
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
20000,
//Set the amount of time between each execution (in milliseconds)
40000);
解决方案
您可以使用Timer.cancel()
终止此计时器,丢弃任何当前计划的任务。不干扰当前正在执行的任务(如果存在)。一旦计时器被终止,它的执行线程就会优雅地终止,并且不能在其上安排更多任务。
将定时器声明为全局
t = new Timer();
试试这个
@Override
protected void onPause() {
super.onPause();
t.cancel();
}
当应用程序到达 onResume(); 时,计时器应该开始工作:
你需要从Timer
试试 onResume()
这个
@Override
protected void onResume() {
super.onResume();
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// code here
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
20000,
//Set the amount of time between each execution (in milliseconds)
40000);
}
推荐阅读
- flutter - 将新对象插入列表后如何更新 ListView?
- python - Selenium,Python - 试图点击 react-text 标签或点击它所属的类的第 n 次出现会导致错误“找不到元素”
- amazon-web-services - 当您将计费模式从 PROVISIONED 更改为 PAY_PER_REQUEST 时,现有 DynamoDB 表中的数据会发生什么情况?
- stata - 在 Slurm 上运行 Stata 作业但出现错误:stata: command not found
- python - Azure 函数已成功发布,但在 Azure 门户中缺失
- kotlin - 编写多行文本的更好方法
- ruby-on-rails - 我可以在 rails 中读取 file_store 缓存文件的内容吗?
- salesforce - Salesforce LWC FullCalendar V5 初始化问题
- powershell - 静默bat文件执行powershell命令
- azure - 在 Azure Synapse 中预先计算 OLAP 多维数据集