10

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?

I am a Student
  • 1,570
  • 4
  • 21
  • 36

2 Answers2

15

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.

Blodhgard
  • 9,130
  • 3
  • 24
  • 36
nst0022
  • 407
  • 2
  • 11
  • 1
    What should I use if I just changed the `repeatInterval` for periodic work (e.g. I want it to run more often)? Will using `KEEP` honor the new repeating interval? – c0dehunter Aug 26 '20 at 02:00
  • 1
    @PrimožKralj you should REPLACE, else the timing interval change will be ignored. – Raunak Sett Sep 27 '20 at 04:46
5

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.

Algar
  • 5,734
  • 3
  • 34
  • 51