How to retry work with every 5 seconds? And if was successful then cancel it?
With the solution below it runs every 10 seconds + Linear growth of time.
// 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()
}
}
That is not possible with the 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
The repeat interval must be greater than or equal to PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS.
And the value of PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS
is 900000, meaning it is equal to 15 minutes.