Most of the apps uses schedulers to schedule task that are executed outside of the life cycle i.e even when the app isn’t running. Tasks such as checking the server for updates, pushing analytics events etc. There are several API’s for scheduling tasks, but not all fits the every use-case.
Lets go through all the API’s and decide the best one for each use case.
JobScheduler was added in API Level 21, this is used to schedule jobs in the application’s own process. It helps scheduling jobs in most efficient way, taking into account the battery status, phone charging status, and also the network status i.e if the network is metered or unmetered.
Advantages of using Job Scheduler ?
- Tasks that should be executed only when the device is in charging mode.
- Tasks that are executed periodically, e.g pushing analytical event daily.
- Tasks that should be executed only on WIFI.
How to use Job Scheduler?
JobService : JobService class is used for implementing the onStartJob() and onStopJob(). This has to be registered with your manifest file.
onStartJob() : is the method where we define the callback code for the jobs, and it is executed on the Main thread. If the job can be done on the main thread, return false, else if it is a long-running job and has to be done async, return true.
onStopJob() : is called when the job stops, maybe due to some paramater mismatch such as when user unplugs the device from charging. Return true if you want to reschedule the job incase it fails due to some reason.
JobInfo : JobInfo is used for creating the job with specified parameters for scheduling.
NOTE : JobScheduler is compatible only with API Level 21 and above. For backport, GCM Network Manager is used.
GCM Network Manager is used as a backport for JobScheduler for below API level 21. It internally uses JobScheduler for API 21 and above.
This uses the Google Play Services to help schedule and batch jobs across the system. Tasks Builder(replacement of JobInfo) are used to define an one-time or a periodic task, and the system takes care of optimizing the battery usage by automatically batching the tasks.
How to use GCM Network Manager?
GcmTaskService : This is used to receive the notification from the scheduler that a task is ready to be executed. We will implement this service and subclass the onRunTask() method to do our job. This has to be registered with your manifest file.
Tasks : There are two types of tasks, OneoffTask and PeriodicTask.
- OneoffTask : A task that is executed once, at some point within the specified window.
- PeriodicTask : Task that is executed at the specified interval, without needing to be rescheduled.
GcmNetworkManager, and JobScheduler fits the use case when the job has to be repeated or one-off, while keeping battery life in mind. If some kind of precision is required in the timing, AlarmManager should be used.
Eg : An alarm app should use AlarmManager, instead of GcmNetworkManager, or JobScheduler.