Skip to content

Instantly share code, notes, and snippets.

@iniyan455
Last active April 19, 2024 12:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iniyan455/b367d478a0195cc5049ef942e1ad4d98 to your computer and use it in GitHub Desktop.
Save iniyan455/b367d478a0195cc5049ef942e1ad4d98 to your computer and use it in GitHub Desktop.
Work Manager Understanding
Work Manager
WorkManager is an API that makes it easy to schedule deferrable, asynchronous tasks that are expected to run even if the app exits or the device restarts. The WorkManager API is a suitable and recommended replacement for all previous Android background scheduling APIs
Device support from 14 -22 it will work on alarm manager with broadcast to process scheduling and GCM NetworkManager
Device above 23 + all uses JobSchedular
usecases :
Dynamic Feature modules and clean architecture
Backup chat like whatsapp after a hours or 1 in a day
update news in any news app - phone in charge or connect with constraint and executes the task and impl
upload image from your app
upload files in dropbox
Delete completed task from doto your todo app
Features
Work Constraints (for example run only when the device connected with wifi or network , device idle or insufficient storage space etc..,
Robost scheduling ( allows to work scheduled work or one time or repeated using flexible scheduling window and work can be tag and named as well , when device is idle or insufficient storage space)
Flexibile retry policy
Sometimes work fails. WorkManager offers flexible retry policies, including a configurable exponential backoff policy.
Work Chaining
For complex related work, chain individual work tasks together using a fluent, natural, interface that allows you to control which pieces run sequentially and which run in parallel
WorkManager is intended for work that is deferrable—that is, not required to run immediately—and required to run reliably even if the app exits or the device restarts. For example:
Sending logs or analytics to backend services
Periodically syncing application data with a server
WorkManager is not intended for in-process background work that can safely be terminated if the app process goes away or for work that requires immediate execution.
Finally, if you need to create a chain of unique work, you can use WorkManager.beginUniqueWork(String, ExistingWorkPolicy, OneTimeWorkRequest) instead of beginWith().
https://github.com/mitchtabian/Clean-Notes
Define the work
Work is defined using the Worker class. The doWork() method is run synchronously on a background thread provided by WorkManager.
The Result returned from doWork() informs the WorkManager service whether the work succeeded and, in the case of failure, whether or not the work should be retried.
Result.success(): The work finished successfully.
Result.failure(): The work failed.
Result.retry(): The work failed and should be tried at another time according to its retry policy.
private val allData: List<File>
get() {
return Common.getListFiles(File(Common.Whatapp_Location_Path), "all")
}
implementation group: 'io.reactivex.rxjava2', name: 'rxjava', version: '2.1.1'
Create a WorkRequest
Once your work is defined, it must be scheduled with the WorkManager service in order to run. WorkManager offers a lot of flexibility in how you schedule your work. You can schedule it to run periodically over an interval of time, or you can schedule it to run only one time.
However you choose to schedule the work, you will always use a WorkRequest. While a Worker defines the unit of work, a WorkRequest (and its subclasses) define how and when it should be run. In the simplest case, you can use a OneTimeWorkRequest
Finally, you need to submit your WorkRequest to WorkManager using the enqueue() method.
Define work requests
Schedule one-time and recurring work
Set work constraints like requiring Wi-Fi or charging
Guarantee a minimum delay in work execution
Set retry and back-off strategies
Pass input data to work
Group related work together using tags
The WorkRequest object contains all of the information needed by WorkManager to schedule and run your work. It includes constraints which must be met for your work to run, scheduling information such as delays or repeating intervals, retry configuration, and may include input data if your work relies on it.
WorkRequest itself is an abstract base class. There are two derived implementations of this class that you can use to create the request, OneTimeWorkRequest and PeriodicWorkRequest
As their names imply, OneTimeWorkRequest is useful for scheduling non-repeating work, whilst PeriodicWorkRequest is more appropriate for scheduling work that repeats on some interval.
The minimum repeat interval that can be defined is 15 minutes (same as the JobScheduler API).
Constraints ensure that work is deferred until optimal conditions are met. The following constraints are available to WorkManager.
Effect of Constraints on Periodic Work
You can apply constraints to periodic work. For example, you could add a constraint to your work request such that the work only runs when the user’s device is charging. In this case, even if the defined repeat interval passes, the PeriodicWorkRequest will not run until this condition is met. This could cause a particular run of your work to be delayed, or even skipped if the conditions are not met within the run interval.
To define periodic work with a flex period, you pass a flexInterval along with the repeatInterval when creating the PeriodicWorkRequest. The flex period begins at repeatInterval - flexInterval, and goes to the end of the interval.
The repeat interval must be greater than or equal to PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS and the flex interval must be greater than or equal to PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS.
Delayed Work
In the event that your work has no constraints or that all the constraints are met when your work is enqueued, the system may choose to run the work immediately. If you do not want the work to be run immediately, you can specify your work to start after a minimum initial delay.
While the example illustrates how to set an initial delay for a OneTimeWorkRequest, you can also set an initial delay for a PeriodicWorkRequest. In that case, only the first run of your periodic work would be delayed.
1.It is used to run some operation in background with periodically without running heavy task on ui thread
2 . Schedule some whatapp backs and example todo completed task need to remove per day or some constraint to perform operation
3. based on constraint it will work updates upload and compression upload to dropbox or server or any constraint like only charging mode or wifi connect time to perform some task
Retry and Backoff Policy
If you require that WorkManager retry your work, you can return Result.retry() from your worker. Your work is then rescheduled according to a backoff delay and backoff policy.
Backoff delay specifies the minimum amount of time to wait before retrying your work after the first attempt. This value can be no less than 10 seconds (or MIN_BACKOFF_MILLIS).
Backoff policy defines how the backoff delay should increase over time for subsequent retry attempts. WorkManager supports 2 backoff policies, LINEAR and EXPONENTIAL.
Every work request has a backoff policy and backoff delay.
val myWorkRequest = OneTimeWorkRequestBuilder<MyWork>()
.setBackoffCriteria(
BackoffPolicy.LINEAR,
OneTimeWorkRequest.MIN_BACKOFF_MILLIS,
TimeUnit.MILLISECONDS)
.build()
In this example, the minimum backoff delay is set to the minimum allowed value, 10 seconds. Since the policy is LINEAR the retry interval will increase by approximately 10 seconds with each new attempt. For instance, the first run finishing with Result.retry() will be attempted again after 10 seconds, followed by 20, 30, 40, and so on, if the work continues to return Result.retry() after subsequent attempts. If the backoff policy were set to EXPONENTIAL, the retry duration sequence would be closer to 20, 40, 80, and so on.
Backoff delays are inexact and could vary by several seconds between retries but will never be less than the initial backoff delay specified in your configuration.
Tag work
Every work request has a unique identifier, which can be used to identify that work later in order to cancel the work or observe its progress.
If you have a group of logically related work, you may also find it helpful to tag those work items. Tagging allows you to operate with a group of work requests together.
Finally, multiple tags can be added to a single work request. Internally these tags are stored as a set of strings. From a work request, you retrieve its set of tags via WorkRequest.getTags().
Once DEBUG logging is enabled, you will start seeing a lot more logs with the log-tag prefix WM-
adb shell dumpsys jobscheduler
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment