22

我有以下一次性工人。

// Create a Constraints that defines when the task should run
Constraints constraints = new Constraints.Builder()
        .setRequiredNetworkType(NetworkType.UNMETERED)
        .setRequiresBatteryNotLow(true)
        // Many other constraints are available, see the
        // Constraints.Builder reference
        .build();

OneTimeWorkRequest oneTimeWorkRequest =
        new OneTimeWorkRequest.Builder(SyncWorker.class)
                .setConstraints(constraints)
                .addTag(SyncWorker.TAG)
                .build();

根据https://developer.android.com/topic/libraries/architecture/workmanager

// (Returning RETRY tells WorkManager to try this task again
// later; FAILURE says not to try again.)

我想知道,如果SyncWorker继续返回RETRY,重试策略是WorkManager什么?例如,最大重试次数是WorkManager多少?文档对此并不清楚。

4

3 回答 3

30

默认值为BackoffPolicy.EXPONENTIAL. 我们仅在您要求我们RETRY返回时重试WorkerResult.RETRY或当您所需的限制Worker现在未得到满足时重试。因此,例如,如果您需要一个NETWORK约束,而现在设备失去了其活动Network连接 - 那么Worker将停止并自动重试(当满足约束时)。

有关更多信息,请查看文档

于 2018-05-25T21:33:09.097 回答
15

以下示例在退出前对捕获的异常重试 3 次。

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()
    }
}

注意:默认 BackoffPolicy 是指数型的,第一次重试在 30 秒内(最小重试周期为 10 秒,最大重试周期永远不会超过 18000 秒/5 小时)。

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)
}
于 2019-06-14T14:47:00.613 回答
1

从 获取任何工作的当前运行尝试计数runAttemptCount。请注意,对于定期工作,此值会在周期之间重置。关联 :-

https://developer.android.com/reference/androidx/work/ListenableWorker#getRunAttemptCount()

例子 :

override fun doWork(): Result {

    if (runAttemptCount < maxRetryConstantIWant) {
    ..... 
    .....
    .....
    } else { Result.Failure }
}

runAttemptCount是工人方法。

于 2021-01-25T09:54:27.277 回答