Limit Retry in Work Manager (Retry Policy)

January 22, 2019
Get WorkManager Retry Count

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

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

    private fun run() {
        // do something
    }

    override fun doWork(): Result {
        App.daggerAppComponent.inject(this)
        Timber.d("doWork, attemp=$runAttemptCount")

        if (runAttemptCount > 3) {
            Timber.d("too many failed attemp, give up")
            return Result.failure()
        }

        try {
            run()
        }
        catch (e: Exception) {
            e.printStackTrace()
            // Crashlytics.logException(e)
            return Result.retry()
        }

        Timber.d("success")
        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)
}

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.