AlarmManager 和 ScheduledExecutorService 之间的区别
除了设置准确时间(即午夜)与设置延迟(即 24 小时)之外,使用 AlarmManager
和 ScheduledExecutorService
定期运行任务之间有什么区别?
就我而言,我需要每天晚上运行一些代码来检查新数据,并在有新数据时创建新通知。
谢谢!
Besides setting and exact time (i.e. midnight) versus setting a delay (i.e. 24 hours), what's the difference between using AlarmManager
and ScheduledExecutorService
to run a task periodically?
In my case, I need to run a little bit of code to check for new data every night and create a new notification if there is new data.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ScheduledExecutorService
在您的应用程序进程中运行。如果应用程序进程终止,则所有计划任务都不会运行。因此需要服务
(以便您的流程超出生命周期的“活动”活动部分)。而
AlarmManager
是一直运行的关键系统服务。如果您的应用程序安排了某些操作并被终止,则AlarmManager
可能会再次启动应用程序(通过PendingIntent
)。这里没有人提到的最后一个主要区别是
AlarmManager
了解WakeLock
和电源管理。这意味着AlarmManager
可以在指定时间唤醒Android设备来运行计划任务。而ScheduledExecutorService
对电源管理一无所知,并且只会在设备未处于深度睡眠状态时启动任务(即它可能会错过时间)。ScheduledExecutorService
runs in your application process. If application process dies, none of the scheduled tasks will run. Hence the need forService
(so your process lives beyond Activities active part of lifecycle).While
AlarmManager
is critical system service that runs all the time. And if your application scheduled something and was killed, thenAlarmManager
may start application again (viaPendingIntent
).And the last major difference that no one mentioned here is that
AlarmManager
knows aboutWakeLock
s and power management. This means thatAlarmManager
may wake up Android device at specified time to run scheduled task. WhileScheduledExecutorService
knows nothing about power management and will only start task when device is not in deep sleep (i.e. it can simply miss the time).仅当您有某个组件(例如
Service
)始终运行时,ScheduledExecutorService
才会起作用。因此,它应该只在组件由于其他原因而位于内存中的情况下使用,从而为用户增加价值。将组件放在内存中只是为了观察时钟的滴答声,这是一种浪费,这也是用户使用任务杀手等攻击开发人员的原因之一。AlarmManager
是操作系统提供的系统服务。当时间到来时它可以启动一个组件。因此,您不需要运行该组件。这是
AlarmManager
的一个清晰场景。ScheduledExecutorService
will only work if you have some component, such as aService
, running all of the time. Hence, it should only be used in cases where the component would be in memory for other reasons, adding value to the user. Having a component be in memory solely to watch the clock tick by is wasteful and one of the reasons why users attack developers with task killers and such.AlarmManager
is an OS-supplied system service. It can start up a component when the time rolls around. Hence, you do not need to have the component running.This is a clear scenario for
AlarmManager
.我认为
ScheduledExecutorService
与您的进程相关联,如果您的进程被终止,则该服务将不起作用。相比之下,AlarmManager
由操作系统管理,因此即使您的应用程序未运行它也可以工作。I think
ScheduledExecutorService
is tied to your process and will not work in case your process gets killed. In contrastAlarmManager
is managed by the OS so it works even if your application is not running.