如何每5秒重试一次?
如果成功,则取消它吗?

使用下面的解决方案,它每10秒运行+时间线性增长。

// todo: schedule, and invoke worker every 5 seconds
// todo: if the work is done and there is no more work in queue - cancel worker.

fun scheduleBatchUpload(uniqueWorkName: String) {
    val logBuilder = PeriodicWorkRequest.Builder(StreamLogWorker::class.java, 5, TimeUnit.SECONDS)

    logBuilder.setBackoffCriteria(BackoffPolicy.LINEAR, 5000, TimeUnit.MILLISECONDS) // Custom retry not working

    WorkManager.getInstance().enqueueUniquePeriodicWork(uniqueWorkName, ExistingPeriodicWorkPolicy.REPLACE, logBuilder.build())
}


class StreamLogWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {

    override fun doWork(): Result {
        Log.e("!!!!!!!!!!", "doWork")
        return Result.retry()
    }
}

最佳答案

您可以尝试手动安排任务,也许可以帮助您实现目标。

private fun WorkManager.launchFrequentTask() {
    val request = OneTimeWorkRequestBuilder<StreamLogWorker>()
            .setInitialDelay(5, TimeUnit.SECONDS)
            .build()
    enqueueUniqueWork(UNIQUE_WORK_NAME, ExistingWorkPolicy.APPEND, request)
}

class StreamLogWorker(private val context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {

    override fun doWork(): Result {
        try {
            // TODO doWork
        } catch (th: Throwable) {
            // log error
        }
        WorkManager.getInstance(context).launchFrequentTask()
        return Result.success()
    }
}


不知道这是否真的如您所愿(每5秒),是否有必要进行检查。

07-27 23:41