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

Viewed 2104

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.

1 Answers

you've used TimeUnit.SECONDS with setInitialDelay yet getDelayTime is working with milliseconds.

This maybe the cause of you problems

Related