What are the retry strategy/ mechanism for WorkManager's OneTimeWorkRequest

The default is BackoffPolicy.EXPONENTIAL. We only retry when you ask us to RETRY by returning WorkerResult.RETRY or when constraints that were required for your Worker are now unmet. So for e.g. if you required a NETWORK constraint, and now the device lost its active Network connection - then the Worker will be stopped and be automatically retried (when the constraints are met).

For more information look at the docs.


This following example retry 3 times on caught Exception before quit.

class RepeatWorker(context : Context, params : WorkerParameters)
    : Worker(context, params) {

    private fun doSomeThing() {
        // do something
    }

    override fun doWork(): Result {

        if (runAttemptCount > 3) {
            return Result.failure()
        }

        try {
            doSomeThing()
        }
        catch (e: Exception) {
            e.printStackTrace()
            return Result.retry()
        }
        return Result.success()
    }
}

NOTE: Default BackoffPolicy is exponential, where 1st retry in 30s (minimum retry period is 10s and maximum retry period never exceed 18000s/5 hours).

fun start() : LiveData<WorkInfo> {
    val WORK_NAME = "SingleBackupWorker"

    val constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build()

    val work = OneTimeWorkRequestBuilder<BackupWorker>()
            .setConstraints(constraints)
            .setInitialDelay(5, TimeUnit.SECONDS)
            .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 1, TimeUnit.MINUTES)
            .build()

    WorkManager.getInstance().enqueueUniqueWork(WORK_NAME, ExistingWorkPolicy.REPLACE, work)

    return WorkManager.getInstance().getWorkInfoByIdLiveData(work.id)
}