简体   繁体   中英

How to run WorkManager's work retry every 5 seconds

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM