将初始延迟设置为Android中的周期性工作管理器 [英] Set initial delay to a Periodic Work Manager in Android
问题描述
我有一个Worker
实例,它需要每24小时运行一次,考虑到PeriodicWorkRequest
API,这非常简单.但这是要抓住的地方.
I have a Worker
instance that needs to run every 24 hours which is pretty simple considering the PeriodicWorkRequest
API. But here's the catch.
如果用户在晚上8点开始工作,那么我需要工作管理器的第一个实例在第二天早上9点运行,然后遵循24小时定期限制.
If the user initiates the work at say 8 PM, I need the first instance of the work manager to run at 9 AM the next morning and then follow the 24-hour periodic constraint.
我在此处发现OneTimeWorkRequest API具有可以使用的setInitialDelay()
函数,但是我找不到PeriodicWork
API的任何内容.
I looked hereand I found that the OneTimeWorkRequest API has a setInitialDelay()
function that can be used but I wasn't able to find anything for the PeriodicWork
API.
还有一些技巧,例如我可以在初始延迟时使用OneTimeWork
,然后从那里安排PeriodicWork
,但这有点脏.
Ther are some hacks for this such as I can use the OneTimeWork
with the initial delay and then schedule a PeriodicWork
from there but it's kinda a dirty hack.
仅使用PeriodicWorkRequest
API有没有办法做到这一点?
Is there any way to do this with just the PeriodicWorkRequest
API?
推荐答案
On the new version of Work manager (Version 2.1.0-alpha02 released on May 16, 2019) PeriodicWorkRequests now support initial delays. You can use the setInitialDelay method on PeriodicWorkRequest.Builder to set an initial delay.
示例:
PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(
WorkerReminderPeriodic.class,
24,
TimeUnit.HOURS,
PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS,
TimeUnit.MILLISECONDS)
.setInitialDelay(1, TimeUnit.HOURS)
.addTag("send_reminder_periodic")
.build();
WorkManager.getInstance()
.enqueueUniquePeriodicWork("send_reminder_periodic", ExistingPeriodicWorkPolicy.REPLACE, workRequest);
这篇关于将初始延迟设置为Android中的周期性工作管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!