本文介绍了如何在 doWork() 调用后更新 PeriodicWorkRequest 的 timeInterval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 android 工作管理器的新手,我想在收到服务器响应后更新 PeriodicWorkRequest 的 timeInterval.这是我尝试更新 timeInterval 的示例代码.但它会进入调用 doWork() 函数的无限循环.请告诉我哪里错了.

I'm new to Work manager in android and I want to update the timeInterval of PeriodicWorkRequest once I got the response from server. Here is my sample code where I'm trying to update the timeInterval. But it is going to an infinite loop of calling the doWork() function. Please suggest to me where it is wrong.

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

private val min = 0
private val max = 100
var randomNumber = 0
var context: Context

init {
    Log.d(TAG, "Constructor invoked")
    this.context = context
    Log.d(TAG, "" + workerParams.id.toString())
}

private fun startRandomNumberGenerator() {
    Log.d(TAG, "startRandomNumberGenerator: isStopped: $isStopped")
    var i = 0
    while (i < 5) {
        try {
            Thread.sleep(1000)
            randomNumber = Random().nextInt(max) + min
            Log.d(
                TAG,
                "Thread Id: " + Thread.currentThread().id + " Random Number: " + randomNumber
            )
            i++
        } catch (e: Exception) {

        }

        if (i == 5) {
            callUpdateSyncTime()
        }
    }

}

private fun callUpdateSyncTime() {
    Log.d(TAG, "callUpdateSyncTime() called")

    val periodicWork =
        PeriodicWorkRequest.Builder(RandomNumberGenerator::class.java, 20, TimeUnit.MINUTES)
            .build()

    WorkManager.getInstance(context)
        .enqueueUniquePeriodicWork(
            "work_manager_random",
            ExistingPeriodicWorkPolicy.REPLACE,
            periodicWork
        )
}

companion object {
    const val TAG = "WorkManager"
}

override fun doWork(): Result {
    startRandomNumberGenerator()
    return Result.success()
}

override fun onStopped() {
    Log.d(TAG, "onStopped() called")
    super.onStopped()
}

}

这是我如何从 MainActivity 排队的代码

Here is the code how I'm enqueuing from my MainActivity

val workRequestRandomNumber: PeriodicWorkRequest =
        PeriodicWorkRequestBuilder<RandomNumberGenerator>(
            15,
            TimeUnit.MINUTES
        ).build()
    workManager.enqueueUniquePeriodicWork(
        "work_manager_random",
        ExistingPeriodicWorkPolicy.KEEP,
        workRequestRandomNumber
    )

推荐答案

当您将 PeriodicWorkRequest 入队时,如果您不使用 setInitialDelay().

When you enqueue a PeriodicWorkRequest, it will be executed immeditially if you don't add an initial delay using setInitialDelay().

考虑到您每次完成后都会重新安排您的工作人员,我建议使用 OneTimeWorkRequest,而不是重复的,并带有初始延迟:

Given that you are rescheduling your worker each time it's completed, I would suggest to use a OneTimeWorkRequest, instead of a repeating one, with an initial delay:

val workRequestRandomNumber =
        OneTimeWorkRequestBuilder<RandomNumberGenerator>()
            .setInitialDelay(
                15,
                TimeUnit.MINUTES)
            .addTag("work_manager_random")
            .build()

workManager.enqueue(workRequestRandomNumber)

就目前而言,WorkManager 正在向您的工作人员发送您忽略的取消通知.

As it is right now, WorkManager is sending a cancellation to your worker that you are ignoring.

这篇关于如何在 doWork() 调用后更新 PeriodicWorkRequest 的 timeInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-10 03:49