android - Why does WorkManager repeat the launch of a successfully completed Worker? - Stack Overflow

I can't understand why the WorkManager runs the Worker twice, not always just one of the many runs

I can't understand why the WorkManager runs the Worker twice, not always just one of the many runs.

For example, method enqueueWorkers receives an array with one element and enqueues it as a OneTimeWorkerRequest without any backoff policies. Even if array have many items, each unique with trigger id from database. The doWork() method executes successfully, without any exceptions. Why success? Because inside executor.waitFinish writes logs to database with default behaviour and expected end. However, in the background inspector from Android Studio, I see that the run count is 2 and the retries are 1. As I understand this is not a duplicate request, it is a re-run of the same.

Does the WorkManager catch any exceptions behind me? Or what the reason retry successful work?

private fun enqueueProgramWorkers(triggers: List<QueueDateTriggerModel>) {
    if (triggers.isEmpty()) {
        return
    }
    val triggerRequests = triggers.map {
        val tag = createTriggerTag(it.trigger.id)
        workManager.cancelAllWorkByTag(tag)
        OneTimeWorkRequestBuilder<ProgramWorker>()
            .setInputData(ProgramWorker.workDataOf(it.trigger.programId, EnqueueSource.DATE_TRIGGER, it.trigger.id))
            .setInitialDelay(it.delayToLaunch, TimeUnit.MILLISECONDS)
            .addTag(tag)
            .build()
    }
    workManager.enqueue(triggerRequests)
}

@HiltWorker
class ProgramWorker @AssistedInject constructor(
    @Assisted private val context: Context,
    @Assisted params: WorkerParameters,
    private val executor: Executor,
) : CoroutineWorker(context, params) {

    override suspend fun doWork(): Result = withContext(ioScope.coroutineContext)  {
        val model = ProgramWorkerModel(inputData)
        setForeground()
        executor.waitFinish(model.programId)
        return@withContext Result.success()
    }

    suspend fun setForeground() {
        try {
            setForeground(getForegroundInfo())
        } catch (error: IllegalStateException) {
            Log.d("ProgramWorker ", error.message.toString())
        }
    }

    companion object {
        fun workDataOf(programId: Int, enqueueSource: EnqueueSource, triggerId: Int = NEW_ID): Data {
            return workDataOf(
                PROGRAM_ID to programId,
                ENQUEUE_SOURCE to enqueueSource.name,
                TRIGGER_ID to triggerId
            )
        }
    }

}
implementation "androidx.work:work-runtime-ktx:2.10.0"

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745039551a4607730.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信