为什么使用WorkManager的OneTimeWorkRequest的setInitialDelay()函数,改变设备时间时延迟不适用 [英] Why use the OneTimeWorkRequest's setInitialDelay() function of the WorkManager, the delay does not apply when changing the device's time

查看:47
本文介绍了为什么使用WorkManager的OneTimeWorkRequest的setInitialDelay()函数,改变设备时间时延迟不适用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 WorkManager 从午夜开始每 24 小时更新一次数据库.

首先,我知道 Workmanager 的 PeriodicWorkRequest 没有指定工人应该在任何给定时间工作.

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

所以我使用 OneTimeWorkRequest() 给出延迟,然后将 PeriodicWorkRequest() 放入队列中,该队列每 24 小时运行一次.

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

1.约束

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

2.OneTimeWorkRequest

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

getDelayTime() is

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

3.MidnightWorker 类

3.MidnightWorker Class

class MidnightWorker : Worker() {

    override fun doWork(): Result {

        DailyWorkerUtil.applyDailyWorker()

        return Worker.Result.SUCCESS
    }
}

4.PeriodicWorkRequest

4.PeriodicWorkRequest

fun applyDailyWorker() {

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

    workManager.enqueue(periodicWorkRequest)

}

并且我确认延迟时间过去了并且midnightWorker正在运行.

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

这是我的问题.

1.根据设备时间没有延迟.我想知道延迟是否符合服务器时间标准.

2.我想知道PeriodicWorkRequest是否可以像OneTimeWorkRequest一样提供InitialDelay.

推荐答案

您已经使用 TimeUnit.SECONDSsetInitialDelaygetDelayTime 是以毫秒为单位工作.

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

这可能是你出现问题的原因

This maybe the cause of you problems

这篇关于为什么使用WorkManager的OneTimeWorkRequest的setInitialDelay()函数,改变设备时间时延迟不适用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆