madim
madim

Reputation: 804

What is the best place to enqueueUniquePeriodicWork?

I want to sync db with server data once a day, and what is the best place to enqueue the work, so it only runs once a day? WorkManager doesn't seem to care if the next enqueue call is within repeatInterval. If I put enqueueing work in Application class, and if that work is completed, WorkManager will run it again if I close and open the app.

Does it mean that I always have to check if the work is enqueued before calling WorkManager.enqueue()?

val workInfo = workManager.getWorkInfosForUniqueWork("UNIQUE_WORK_NAME").get()?.getOrNull(0)
if (workInfo?.state == WorkInfo.State.ENQUEUED) {
    // do nothing
    return
}

workManager.enqueueUniquePeriodicWork(
                "UNIQUE_WORK_NAME",
                ExistingPeriodicWorkPolicy.KEEP,
                PeriodicWorkRequestBuilder<SyncDbWorker>(
                        1,
                        TimeUnit.DAYS
                )
                .setConstraints(constraints)
                .build())

UPDATE:

One thing I forgot to mention is that inside my Worker I always return Result.success(). So if the work fails for some reason WorkManager will retry it on the next iteration.

Upvotes: 5

Views: 1380

Answers (1)

pfmaggi
pfmaggi

Reputation: 6476

You don't need to check if the work is already enqueued when you use enqueueUniquePeriodicWork(). Using Keep as ExistingPeriodicWorkPolicy, will guarantee that the work is only enqueued if there's no other work with the same uniqueWorkName already scheduled.

Said that, the usual place where you can enqueue your unique work is the onCreate() callback in your application. This will guarantee that the job is scheduled.

Keep in mind that a PeriodicWorkRequest can slips over time, as described in the documentation. I've covered this in a talk (around 24:25) I've presented last month with a possible workaround. Support for DailyWorkers is supposed to land in v2.1.x in one of the next alpha releases.

Upvotes: 4

Related Questions