Limit Retry in Work Manager (Retry Policy)

Jan 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:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.