Analyzing in Depth Work Manager
@bhatnagar_g @rohankandwal
Existing Problems
Battery Issues
How is battery utilized in Android
Screen Off Screen On
CPU Radios Screen
e.g. wakelocks e.g. syncs, network activity
Background Activity
Existing battery saving techniques
Design Principles
Reduce Defer Coalesce
Reduce all background activity If background activity must be
performed, defer it to when
device is on charger
If it cannot be deferred,
coalesce it with other
background activity to reduce
wakeup overhead
Optimization efforts in Android
Doze Mode and App Standby
Native Support for Doze on the Go (Nougat)
Juxtaposition between Extended & Deep Doze
Doze Extended
Trigger Screen off, on battery, stationary Screen off , on battery
Timing
Successively increasing periods with
maintenance windows
Repeated N-minute periods with
maintenance windows
Restrictions
No Network Access
Jobs/Syncs deferred
No Wakelocks
Alarms deferred
No GPS/WiFi Scans
No Network Access
Jobs/Syncs deferred
Exit
Motion, screen on, alarm clock or device
charging
Screen on or device charging
Background Processing Limitations (Oreo)
● To Improve RAM / Battery performance.
● Restricting Background processes for different applications
○ Services run freely in foreground
○ Background services are stopped when idle.
○ Bound services are not affected.
● Limitations on Background Location Updates
○ When in Background apps to receive location updates only a few times each hour.
● Broadcast Restrictions (very short list of excluded implicit broadcasts)
Adaptive Battery & Adaptive Brightness
App Standby Buckets
● Active
● Working Set
● Frequent
● Rare
● Never
Application is in
Active Bucket
Has a notification from the
app been clicked
Is a sync adapter being
used in foreground?
Is there a foreground
service running?
Has an activity been
launched?
Is the application not often
used?
Is the application used
regularly?
Is the application used most
days?
Application is in
Never Bucket
Application is in
Working Set Bucket
Application is in
Frequent Bucket
Application is in
Rare Bucket
Yes
Yes
Yes
Yes
Yes
Yes
Yes
No
No
No
Application is not
currently active
No
No
No
No
Existing solutions for background tasks
Async Task
Job Scheduler
Loaders
Alarm Manager
Sync Adapter
Firebase JobDispatcher
Service
Executors/Threads
Android Job (Evernote)
Android Jetpack
Work Manager
Work Manager
● WorkManager is the recommended solution for background execution, taking into
account all OS background execution limits.
● The work is guaranteed to run, even on app restart.
● Work Manager is backward compatible to API 14.
● Works with and without Google Play Services.
● It should be used for all deferrable and guaranteed background work.
Internal Mechanism of WorkManager
Work Manager
API
23+
Job scheduler
Has play
services?
Alarm Manager and broadcast
receiver
GCM Network Manager
Yes
Yes
No
No
Worker
● Synchronous and runs on background thread by default
● doWork() method is overridden and the task added in it.
● doWork() is called exactly once per Worker instance. A new Worker is created if a unit of
work needs to be rerun.
● A Worker is given a maximum of ten minutes to finish its execution and return a
ListenableWorker.Result. After this time has expired, the Worker will be signalled to
stop.
Worker internal mechanism
Worker
doWork()
Result
Failure Success Retry
ListenableWorker
● Work asynchronously
● Instantiated at runtime by the WorkerFactory specified in the Configuration.
● startWork() method performs all the task and runs on the main thread.
● New instance of ListenableWorker is case of a new or restarted work.
● Maximum of ten minutes to finish execution.
● Return a ListenableWorker.Result
Work Manager Request Types (1/2)
YesNo
Work Manager Request Types (2/2)
1. One Time Request
a. It is used for non-repeating work which can be part of a chain
b. It could have an initial delay
c. It could be part of a chain or graph of work
2. Periodic Request
a. Used for tasks that need to execute periodically but interval has to be more than 15 minutes
which will be be in flex interval.
b. It cannot be part of a chain or graph of work
One-Time Work Cycle
BLOCKED ENQUEUED RUNNING SUCCEEDED
CANCELLED
FAILED
RETRY
CANCEL
FAILURE
SUCCESS
Demo
// Creating an one time worker object
Periodic Work Cycle
ENQUEUED RUNNING
CANCELLED
FAILED
RETRY
CANCEL
SUCCESS
FAILURE
Demo
// Creating a periodic work request which will execute every 15 minutes
Add Constraints
// Create constraint for to specify battery level and network type
//Request object to report it to the server
Start the task
Before v2.1
// Enqueuing the work request to fire the Work request
After v2.1
// Enqueuing the work request to fire the Work request
Input/Output for the task
// Input data for task while creating a Worker
// Setting data as input for the worker
// Reading data in Worker class
// Setting output from worker
// Return the data back in Result
Delays and Retries
Initial Delay
Retries
BackOff Policy :
Tagging of Tasks
Tags are meant to be used as categories, to identify/classify similar pieces of work that we
might want to operate on as a bunch.
Unique work
Prevent duplicate tasks for the app.
Observe work status
Retrieve WorkInfo
Chaining Work Example
Periodic Worker
(Fired every 30 minutes)
Get RemoteConfig Worker
(gets remote configuration)
BatteryStats Worker
(reads device’s battery info)
NetworkStats Worker
(reads network info)
ReportGenerator Worker
(creates report and send to server)
Initializes Remote Config Worker
Gets info from
network and set as
Output data
Read configurations from
RemoteConfig Worker &
output it’s data
Read data from
BatteryStats &
NetworkStats worker
Read configurations from
RemoteConfig Worker &
output it’s data
One Time Worker
Periodic Worker
Chaining Work in Code
Added in Periodic Worker
Life of chain (1/4)
Enqueued
Blocked Blocked
Blocked Blocked
Blocked Blocked
A
B
D
F G
E
C
Life of chain (2/4)
Running
Blocked Blocked
Blocked Blocked
Blocked Blocked
A
B
D
F G
E
C
Life of chain (3/4)
Succeeded
Enqueued Enqueued
Blocked Blocked
Blocked Blocked
A
B
D
F G
E
C
Life of chain (4/4)
Succeeded
Succeeded Failed
Enqueued Failed
Failed Failed
A
B
D
F G
E
C
Work Continuation
Work Continuation
Cancelling work
// Cancel work by work request ID
WorkManager.getInstance(this).cancelWorkById(workRequest.id)
// Cancel work by unique work tag
WorkManager.getInstance(this).cancelAllWorkByTag(String)
// Cancel work
WorkManager.getInstance(this).cancelUniqueWork(String)
Threading in Work Manager
Threading in WorkManager
Internal
TaskExecutor
Listenable
Worker
addListener()Constraints
Met
WorkerFactory startWork()
Work Manager
Listenable Worker
Simple Worker RxWorker Coroutine Worker*
Listenable Worker
Simple Worker
RxWorker
Co-routine Worker
Handle when Work is stopped
● ListenableWorker's ListenableFuture is always cancelled when the work is expected to stop.
● Accordingly you can use the cancellation listener also to receive the callback.
● Override void onStopped() method for Listenable Worker.
● By handling work stoppages ,we abide by the rules and facilitate clean up.
● Return values or Future results will be ignored.
● It is better to check for stoppages via boolean isStopped() method for ListenableWorker.
Custom configuration
Used for initializing WorkManager with custom configurations, like -
● Factory for Worker and ListenableWorkers
● Default executor for workers
● Custom Logging
● various Job Scheduler parameters
Dependency Injection in Worker
● WorkManager provides an abstract WorkerFactory class which our factory can use to instantiate workers.
Source - https://bit.ly/2ZF8TBQ
● Assisted Injection library provided by Square
Source - http://bit.ly/wmsamples
● Dagger2 Multi-binding
Source - https://bit.ly/2L7Afwm
Testing
What to use?
References
● http://bit.ly/2ZuNRtT - Work Manager Series by Pietro Maggi
● http://bit.ly/2L7ZNK1 - Work Manager with RxJava by Paulina Sadowska
● http://bit.ly/2NLOkBk - Dagger 2 Setup with Work Manager by Tuan Kiet
● http://bit.ly/2HwX3DS - Listenable Future Explained
● http://bit.ly/2MKKUiL - Android Dev Summit Talk on Work Manager by Sumir Kataria & Rahul Ravikumar
● http://bit.ly/30LlZPt - Workout Your tasks with WorkManager by Magada Miu
● http://bit.ly/2MJKbyc - Android Developers Blog: Power series
● http://bit.ly/2LkCdII - Schedule tasks with WorkManager | Android Developers
● http://bit.ly/30M4DBQ - How does Android Optimize Battery Usage in New Releases?
● http://bit.ly/2L5MGc9 - An ~extended~ Doze mode (Android Development Patterns S3 Ep 3) - YouTube
● http://bit.ly/2ZC3n2P - Android Jetpack: easy background processing with WorkManager - YouTube
Q & A

More Related Content

PDF
Queue your work
PDF
Gearman: A Job Server made for Scale
PDF
LCA13: Combining Runtime PM and suspend/resume
PDF
Gearman and Perl
PDF
Gatling - Bordeaux JUG
PPTX
Performance tests with Gatling
PPT
Gearman - Job Queue
PDF
Khanh-Nguyen - Gearman - distributed process solution
Queue your work
Gearman: A Job Server made for Scale
LCA13: Combining Runtime PM and suspend/resume
Gearman and Perl
Gatling - Bordeaux JUG
Performance tests with Gatling
Gearman - Job Queue
Khanh-Nguyen - Gearman - distributed process solution

What's hot (11)

PDF
Not Quite As Painful Threading
PDF
Oracle中加速索引创建或重建的方法
PDF
Advanced task management with Celery
PDF
Faster PHP apps using Queues and Workers
PDF
How to add non root user account to netapp for commvault
PDF
React loadable
PDF
Celery
PPTX
Stress driven development
PDF
Rails Application Optimization Techniques & Tools
ODP
Performance Optimization of Rails Applications
KEY
Gearman and CodeIgniter
Not Quite As Painful Threading
Oracle中加速索引创建或重建的方法
Advanced task management with Celery
Faster PHP apps using Queues and Workers
How to add non root user account to netapp for commvault
React loadable
Celery
Stress driven development
Rails Application Optimization Techniques & Tools
Performance Optimization of Rails Applications
Gearman and CodeIgniter
Ad

Similar to Analysing in depth work manager (20)

PDF
Analysing in depth work manager
PPTX
Android scheduling.pptx
PPTX
Von neumann workers
PDF
FuzzyDebugger.pdf
PDF
What's new in WorkManager-Andri Suranta Ginting (Product Engineer-Gojek)
PDF
Bootstrapping a ML platform at Bluevine [Airflow Summit 2020]
PDF
Android Best Practices - Thoughts from the Trenches
PDF
"Scaling in space and time with Temporal", Andriy Lupa.pdf
PDF
Distributed Queue System using Gearman
PDF
"Scaling in space and time with Temporal", Andriy Lupa .pdf
DOCX
A Project Run@Timer, J2SE,
PPTX
Easy job scheduling with android
PDF
Migrating From Foreground Services To WorkManager
PPT
Writing Prefork Workers / Servers
PDF
PyGrunn2013 High Performance Web Applications with TurboGears
PDF
Prometheus and Docker (Docker Galway, November 2015)
PPTX
How many ways to monitor oracle golden gate-Collaborate 14
PPTX
Web worker
PDF
Advanced android app development
PDF
OSMC 2012 | Shinken by Jean Gabès
Analysing in depth work manager
Android scheduling.pptx
Von neumann workers
FuzzyDebugger.pdf
What's new in WorkManager-Andri Suranta Ginting (Product Engineer-Gojek)
Bootstrapping a ML platform at Bluevine [Airflow Summit 2020]
Android Best Practices - Thoughts from the Trenches
"Scaling in space and time with Temporal", Andriy Lupa.pdf
Distributed Queue System using Gearman
"Scaling in space and time with Temporal", Andriy Lupa .pdf
A Project Run@Timer, J2SE,
Easy job scheduling with android
Migrating From Foreground Services To WorkManager
Writing Prefork Workers / Servers
PyGrunn2013 High Performance Web Applications with TurboGears
Prometheus and Docker (Docker Galway, November 2015)
How many ways to monitor oracle golden gate-Collaborate 14
Web worker
Advanced android app development
OSMC 2012 | Shinken by Jean Gabès
Ad

Recently uploaded (9)

DOC
SIUE毕业证学历认证,阿祖萨太平洋大学毕业证学位证书复制
PPTX
Introduction to Packet Tracer Course Overview - Aug 21 (1).pptx
DOC
EIU毕业证学历认证,贝尔维尤学院毕业证国外毕业证
PDF
Date Right Stuff - Invite only, conservative dating app
PDF
2025 Guide to Buy Verified Cash App Accounts You Can Trust.pdf
DOC
NIU毕业证学历认证,阿比林基督大学毕业证留学生学历
PPTX
Social Media People PowerPoint Templates.pptx
PDF
Kids, Screens & Emotional Development by Meenakshi Khakat
PDF
Best 4 Sites for Buy Verified Cash App Accounts – BTC Only.pdf
SIUE毕业证学历认证,阿祖萨太平洋大学毕业证学位证书复制
Introduction to Packet Tracer Course Overview - Aug 21 (1).pptx
EIU毕业证学历认证,贝尔维尤学院毕业证国外毕业证
Date Right Stuff - Invite only, conservative dating app
2025 Guide to Buy Verified Cash App Accounts You Can Trust.pdf
NIU毕业证学历认证,阿比林基督大学毕业证留学生学历
Social Media People PowerPoint Templates.pptx
Kids, Screens & Emotional Development by Meenakshi Khakat
Best 4 Sites for Buy Verified Cash App Accounts – BTC Only.pdf

Analysing in depth work manager

  • 1. Analyzing in Depth Work Manager @bhatnagar_g @rohankandwal
  • 4. How is battery utilized in Android Screen Off Screen On CPU Radios Screen e.g. wakelocks e.g. syncs, network activity Background Activity
  • 6. Design Principles Reduce Defer Coalesce Reduce all background activity If background activity must be performed, defer it to when device is on charger If it cannot be deferred, coalesce it with other background activity to reduce wakeup overhead
  • 8. Doze Mode and App Standby
  • 9. Native Support for Doze on the Go (Nougat)
  • 10. Juxtaposition between Extended & Deep Doze Doze Extended Trigger Screen off, on battery, stationary Screen off , on battery Timing Successively increasing periods with maintenance windows Repeated N-minute periods with maintenance windows Restrictions No Network Access Jobs/Syncs deferred No Wakelocks Alarms deferred No GPS/WiFi Scans No Network Access Jobs/Syncs deferred Exit Motion, screen on, alarm clock or device charging Screen on or device charging
  • 11. Background Processing Limitations (Oreo) ● To Improve RAM / Battery performance. ● Restricting Background processes for different applications ○ Services run freely in foreground ○ Background services are stopped when idle. ○ Bound services are not affected. ● Limitations on Background Location Updates ○ When in Background apps to receive location updates only a few times each hour. ● Broadcast Restrictions (very short list of excluded implicit broadcasts)
  • 12. Adaptive Battery & Adaptive Brightness
  • 13. App Standby Buckets ● Active ● Working Set ● Frequent ● Rare ● Never Application is in Active Bucket Has a notification from the app been clicked Is a sync adapter being used in foreground? Is there a foreground service running? Has an activity been launched? Is the application not often used? Is the application used regularly? Is the application used most days? Application is in Never Bucket Application is in Working Set Bucket Application is in Frequent Bucket Application is in Rare Bucket Yes Yes Yes Yes Yes Yes Yes No No No Application is not currently active No No No No
  • 14. Existing solutions for background tasks Async Task Job Scheduler Loaders Alarm Manager Sync Adapter Firebase JobDispatcher Service Executors/Threads Android Job (Evernote)
  • 17. Work Manager ● WorkManager is the recommended solution for background execution, taking into account all OS background execution limits. ● The work is guaranteed to run, even on app restart. ● Work Manager is backward compatible to API 14. ● Works with and without Google Play Services. ● It should be used for all deferrable and guaranteed background work.
  • 18. Internal Mechanism of WorkManager Work Manager API 23+ Job scheduler Has play services? Alarm Manager and broadcast receiver GCM Network Manager Yes Yes No No
  • 19. Worker ● Synchronous and runs on background thread by default ● doWork() method is overridden and the task added in it. ● doWork() is called exactly once per Worker instance. A new Worker is created if a unit of work needs to be rerun. ● A Worker is given a maximum of ten minutes to finish its execution and return a ListenableWorker.Result. After this time has expired, the Worker will be signalled to stop.
  • 21. ListenableWorker ● Work asynchronously ● Instantiated at runtime by the WorkerFactory specified in the Configuration. ● startWork() method performs all the task and runs on the main thread. ● New instance of ListenableWorker is case of a new or restarted work. ● Maximum of ten minutes to finish execution. ● Return a ListenableWorker.Result
  • 22. Work Manager Request Types (1/2) YesNo
  • 23. Work Manager Request Types (2/2) 1. One Time Request a. It is used for non-repeating work which can be part of a chain b. It could have an initial delay c. It could be part of a chain or graph of work 2. Periodic Request a. Used for tasks that need to execute periodically but interval has to be more than 15 minutes which will be be in flex interval. b. It cannot be part of a chain or graph of work
  • 24. One-Time Work Cycle BLOCKED ENQUEUED RUNNING SUCCEEDED CANCELLED FAILED RETRY CANCEL FAILURE SUCCESS
  • 25. Demo // Creating an one time worker object
  • 26. Periodic Work Cycle ENQUEUED RUNNING CANCELLED FAILED RETRY CANCEL SUCCESS FAILURE
  • 27. Demo // Creating a periodic work request which will execute every 15 minutes
  • 28. Add Constraints // Create constraint for to specify battery level and network type //Request object to report it to the server
  • 29. Start the task Before v2.1 // Enqueuing the work request to fire the Work request After v2.1 // Enqueuing the work request to fire the Work request
  • 30. Input/Output for the task // Input data for task while creating a Worker // Setting data as input for the worker // Reading data in Worker class // Setting output from worker // Return the data back in Result
  • 31. Delays and Retries Initial Delay Retries BackOff Policy :
  • 32. Tagging of Tasks Tags are meant to be used as categories, to identify/classify similar pieces of work that we might want to operate on as a bunch.
  • 33. Unique work Prevent duplicate tasks for the app.
  • 36. Chaining Work Example Periodic Worker (Fired every 30 minutes) Get RemoteConfig Worker (gets remote configuration) BatteryStats Worker (reads device’s battery info) NetworkStats Worker (reads network info) ReportGenerator Worker (creates report and send to server) Initializes Remote Config Worker Gets info from network and set as Output data Read configurations from RemoteConfig Worker & output it’s data Read data from BatteryStats & NetworkStats worker Read configurations from RemoteConfig Worker & output it’s data One Time Worker Periodic Worker
  • 37. Chaining Work in Code Added in Periodic Worker
  • 38. Life of chain (1/4) Enqueued Blocked Blocked Blocked Blocked Blocked Blocked A B D F G E C
  • 39. Life of chain (2/4) Running Blocked Blocked Blocked Blocked Blocked Blocked A B D F G E C
  • 40. Life of chain (3/4) Succeeded Enqueued Enqueued Blocked Blocked Blocked Blocked A B D F G E C
  • 41. Life of chain (4/4) Succeeded Succeeded Failed Enqueued Failed Failed Failed A B D F G E C
  • 44. Cancelling work // Cancel work by work request ID WorkManager.getInstance(this).cancelWorkById(workRequest.id) // Cancel work by unique work tag WorkManager.getInstance(this).cancelAllWorkByTag(String) // Cancel work WorkManager.getInstance(this).cancelUniqueWork(String)
  • 45. Threading in Work Manager
  • 47. Work Manager Listenable Worker Simple Worker RxWorker Coroutine Worker*
  • 52. Handle when Work is stopped ● ListenableWorker's ListenableFuture is always cancelled when the work is expected to stop. ● Accordingly you can use the cancellation listener also to receive the callback. ● Override void onStopped() method for Listenable Worker. ● By handling work stoppages ,we abide by the rules and facilitate clean up. ● Return values or Future results will be ignored. ● It is better to check for stoppages via boolean isStopped() method for ListenableWorker.
  • 53. Custom configuration Used for initializing WorkManager with custom configurations, like - ● Factory for Worker and ListenableWorkers ● Default executor for workers ● Custom Logging ● various Job Scheduler parameters
  • 54. Dependency Injection in Worker ● WorkManager provides an abstract WorkerFactory class which our factory can use to instantiate workers. Source - https://bit.ly/2ZF8TBQ ● Assisted Injection library provided by Square Source - http://bit.ly/wmsamples ● Dagger2 Multi-binding Source - https://bit.ly/2L7Afwm
  • 57. References ● http://bit.ly/2ZuNRtT - Work Manager Series by Pietro Maggi ● http://bit.ly/2L7ZNK1 - Work Manager with RxJava by Paulina Sadowska ● http://bit.ly/2NLOkBk - Dagger 2 Setup with Work Manager by Tuan Kiet ● http://bit.ly/2HwX3DS - Listenable Future Explained ● http://bit.ly/2MKKUiL - Android Dev Summit Talk on Work Manager by Sumir Kataria & Rahul Ravikumar ● http://bit.ly/30LlZPt - Workout Your tasks with WorkManager by Magada Miu ● http://bit.ly/2MJKbyc - Android Developers Blog: Power series ● http://bit.ly/2LkCdII - Schedule tasks with WorkManager | Android Developers ● http://bit.ly/30M4DBQ - How does Android Optimize Battery Usage in New Releases? ● http://bit.ly/2L5MGc9 - An ~extended~ Doze mode (Android Development Patterns S3 Ep 3) - YouTube ● http://bit.ly/2ZC3n2P - Android Jetpack: easy background processing with WorkManager - YouTube
  • 58. Q & A