[英]How to run WorkManager's work retry every 5 seconds
How to retry work with every 5 seconds?如何每 5 秒重试一次? And if was successful then cancel it?
如果成功则取消它?
With the solution below it runs every 10 seconds + Linear growth of time.使用下面的解决方案,它每 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()
}
}
You can try to schedule your task manually, perhaps it can help to reach your goal.您可以尝试手动安排您的任务,也许它可以帮助您实现目标。
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()
}
}
Not sure if this really works as you want (every 5 seconds), it is necessary to check.不确定这是否真的如您所愿(每 5 秒一次),有必要检查一下。
That is not possible with the PeriodicWorkRequest
.这对于
PeriodicWorkRequest
是不可能的。 if you look at documentation of the the PeriodicWorkRequest.Builder
constructor that you are using, you will see that it says following about the second parameter如果您查看您正在使用的
PeriodicWorkRequest.Builder
构造函数的文档,您会看到它说明了第二个参数
The repeat interval must be greater than or equal to PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS.
重复间隔必须大于或等于 PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS。
And the value of PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS
is 900000, meaning it is equal to 15 minutes.而
PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS
值为900000,即等于15分钟。
The repeat interval must be greater than or equal to PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS(see documentation).重复间隔必须大于或等于 PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS(参见文档)。 Periodic work has a minimum interval of 15 minute
周期性工作的最小间隔为 15 分钟
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.