By referring to: Android WorkManager api for running daily task in Background
It uses the WorkManager.enqueueUniquePeriodicWork
to ensure that PeriodicWorkRequest is not created multiple times.
example code:
val work = PeriodicWorkRequestBuilder<SyncWork>(15,TimeUnit.MINUTES).build()
WorkManager.getInstance().enqueueUniquePeriodicWork("TaskTag",
ExistingPeriodicWorkPolicy.KEEP, work);
However, I found it there is 2 option of ExistingPeriodicWorkPolicy
which is ExistingPeriodicWorkPolicy.KEEP
and ExistingPeriodicWorkPolicy.REPLACE
can be use.
I try to implement it and run the code, but it does really show any differences, and it seem both of them behave the same way.
My uncertainty:
How does the ExistingPeriodicWorkPolicy.KEEP
perform differently from ExistingPeriodicWorkPolicy.REPLACE
?
This second interval (the flexInterval) it's positioned at the end of the repetition interval itself. Let's look at an example. Imagine you want to build a periodic Work request with a 30 minutes period. You can specify a flexInterval, smaller than this period, say a 15 minute flexInterval.
Retry and backoff policyIf 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 method is deprecated. Call getInstance instead.
WorkManager is the recommended solution for persistent work. Work is persistent when it remains scheduled through app restarts and system reboots. Because most background processing is best accomplished through persistent work, WorkManager is the primary recommended API for background processing.
In your example, you are about to enqueue a new work request (a.k.a. worker). If you have done this just before at runtime, this worker is already present with state ENQUEUED.
KEEP: If a previous worker exists, your new attempt is simply ignored, else your new worker is enqueued.
REPLACE: If a previous worker exists, it is cancelled, leading to a state CANCELLED for it. Then or else, your new worker is enqueued.
So, if you are sure that your new worker is the same as the previous one (say the constraints have not changed), then KEEP should be safe, otherwise REPLACE might be the better option.
KEEP: If there is existing pending work with the same unique name, do nothing.
REPLACE: If there is existing pending work with the same unique name, cancel and delete it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With