Reputation: 1978
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()
}
}
Upvotes: 3
Views: 3583
Reputation: 11
The repeat interval must be greater than or equal to PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS(see documentation). Periodic work has a minimum interval of 15 minute
Upvotes: 1
Reputation: 8355
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.
Upvotes: 2
Reputation: 1332
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.
Upvotes: 3