Why use the OneTimeWorkRequest's setInitialDelay() function of the WorkManager, the delay does not apply when changing the device's time

南笙酒味 提交于 2020-01-22 16:00:08

问题


I would like to use WorkManager to update the DB every 24 hours from midnight.

First, I'm understand that the Workmanager's PeriodicWorkRequest does not specify that the worker should operate at any given time.

So I used OneTimeWorkRequest() to give the delay and then put the PeriodicWorkRequest() in the queue, which runs every 24 hours.

1.Constraints

private fun getConstraints(): Constraints {
    return Constraints.Builder()
            .setRequiredNetworkType(NetworkType.NOT_REQUIRED)
            .build()
}

2.OneTimeWorkRequest

fun applyMidnightWorker() {

    val onTimeDailyWorker = OneTimeWorkRequest
            .Builder(MidnightWorker::class.java)
            .setInitialDelay(getDelayTime(), TimeUnit.SECONDS)
            .setConstraints(getConstraints())
            .build()

    val workerContinuation =
            workManager.beginUniqueWork(Const.DAILY_WORKER_TAG,
                    ExistingWorkPolicy.KEEP,
                    onTimeDailyWorker)

    workerContinuation.enqueue()
}

getDelayTime() is

private fun getDelayTime(): Long {
    ...
    return midNightTime - System.currentTimeMillis()
}

3.MidnightWorker Class

class MidnightWorker : Worker() {

    override fun doWork(): Result {

        DailyWorkerUtil.applyDailyWorker()

        return Worker.Result.SUCCESS
    }
}

4.PeriodicWorkRequest

fun applyDailyWorker() {

    val periodicWorkRequest = PeriodicWorkRequest
            .Builder(DailyWorker::class.java, 24, TimeUnit.HOURS)
            .addTag(Const.DAILY_WORKER)
            .setConstraints(getConstraints()).build()

    workManager.enqueue(periodicWorkRequest)

}

And I confirmed that the delayTime passed and the midnightWorker was running.

Of course, It worked normally without any relation to the network.

However, test results showed that the delay time worked regardless of device time. As if it were server time

This is my question.

1. No delay according to device time. I want to know if the delay works as per the server time standard.

2. I wonder if the PeriodicWorkRequest can provide InitialDelay like OneTimeWorkRequest.

来源:https://stackoverflow.com/questions/52088873/why-use-the-onetimeworkrequests-setinitialdelay-function-of-the-workmanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!