在 Android returns 从睡眠中立即执行几次的周期性定时器任务
Periodic timertask executed several times at once after Android returns from sleep
我已经实现了后台服务来定期更新我的应用程序中的数据。
如果我的 android 设备打开,该机制运行良好,但当 Android 处于睡眠模式时会出现问题:
假设服务每 15 分钟 运行ning 一次,然后 Android 休眠 1 小时,当再次变弱时,服务将一次执行 4 次。
首选行为是 运行 仅启用一次服务,以防它因睡眠而错过 1 个或多个周期。
为了 运行 我的代码定期,我正在使用 TimerTask:
public class updateService extends IntentService {
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
if(mTimer != null) {
mTimer.cancel();
}
mTimer = new Timer();
int timer = getPreference("refresh_interval") * 1000;
mTimer.scheduleAtFixedRate(new updateTask (), timer, timer);
return super.onStartCommand(intent, flags, startId);
}
class updateTask extends TimerTask {
@Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
@Override
public void run() {
// Do job
}
});
}
}
}
如果有任何改进建议,我将不胜感激。谢谢!
您正在使用 Timer.scheduleAtFixedRate(TimerTask task, long delay, long period)
,其文档中有说明:
If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up."
您似乎想改用 Timer.schedule(TimerTask task, long delay, long period)
,它表示:
If an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well.
如果由于任何原因(例如垃圾回收或其他背景activity)延迟执行,后续执行也将延迟。他是对的
我已经实现了后台服务来定期更新我的应用程序中的数据。 如果我的 android 设备打开,该机制运行良好,但当 Android 处于睡眠模式时会出现问题:
假设服务每 15 分钟 运行ning 一次,然后 Android 休眠 1 小时,当再次变弱时,服务将一次执行 4 次。 首选行为是 运行 仅启用一次服务,以防它因睡眠而错过 1 个或多个周期。
为了 运行 我的代码定期,我正在使用 TimerTask:
public class updateService extends IntentService {
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
if(mTimer != null) {
mTimer.cancel();
}
mTimer = new Timer();
int timer = getPreference("refresh_interval") * 1000;
mTimer.scheduleAtFixedRate(new updateTask (), timer, timer);
return super.onStartCommand(intent, flags, startId);
}
class updateTask extends TimerTask {
@Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
@Override
public void run() {
// Do job
}
});
}
}
}
如果有任何改进建议,我将不胜感激。谢谢!
您正在使用 Timer.scheduleAtFixedRate(TimerTask task, long delay, long period)
,其文档中有说明:
If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up."
您似乎想改用 Timer.schedule(TimerTask task, long delay, long period)
,它表示:
If an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well.
如果由于任何原因(例如垃圾回收或其他背景activity)延迟执行,后续执行也将延迟。他是对的