Home > Back-end >  Alarm Manager or Work Manager for Recurring Background Work
Alarm Manager or Work Manager for Recurring Background Work

Time:02-01

I'm having trouble deciding whether to run some recurring background work with Alarm Manager or Work Manager:

  • The work is going to consist of Room Database operations so I'll need access to Dao to complete my work.
  • It is going to be recurring at fixed intervals (hourly, daily, weekly, monthly, etc.)
  • I need to set a start date and time for the recurrence intervals.
  • the work will recur until canceled by the user
  • If the user is using the app when the work is supposed to be scheduled, I want the work to be done immediately. If the user is not on the app (app is in the background or device is turned off), I don't care if the work is done after the scheduled time as long as it is at least started by the next time the user opens the app.
  • the work needs to continue as scheduled after device reboots and app restarts.

CodePudding user response:

For recurring background work, AlarmManger isn't suitable. As the name implies, it's intended to notify the system of an event at a precise time. Just like a physical alarm that wakes a person up even if the person sleeps, AlarmManager will wake up the device from doze mode which will result in more power usage. it is suitable for suitations like setting remainders such as for calender events which the users probably set by themselves.

On the other hand, WorkManager is intended to carry out background processing or work that would persist. Workmanager is much more efficient for recurring task especially as it allows you set constraints to determine when it should start or stop the background work.

check the link form the offical documentation on WorkManger: workmanager architecture tabular comparison between the two

CodePudding user response:

It mostly depends on how important your task is.

https://developer.android.com/guide/background is a really good entry point to help you choose what you should work with.

WorkManager is the modern, universal approach of handling background work and it fits for most use-cases, it automatically reschedules work after a device restart or an application crash, and it is very efficient in terms of battery usage.

As WorkManager does respect Android's doze mode, it does not guarantee, that the work will be done exactly on time, though it does guarantee, that your work will be done within a certain time frame.

On the other hand, AlarmManager is capable of running work precisely on time. But this means that the device will wake up when your work scheduled with AlarmManager is coming due. This will drain battery and your app will probably show up as battery-draining in the Device Health board.

But as stated in the article above, prefer using WorkManager if possible. AlarmManager should only be used for e.g. a time-sensitive calendar notification.

  •  Tags:  
  • Related