Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

android - How periodic work works with WorkManager?

I tried to use WorkManager along with PeriodicWorkRequestBuilder, but I've got confused and I didn't find satisfying answer in documentation.

Here's a visualization from docs:

[     before flex     |     flex     ][     before flex     |     flex     ]...
[   cannot run work   | can run work ][   cannot run work   | can run work ]...
\____________________________________/\____________________________________/...
               interval 1                            interval 2             ...(repeat)

Now let's take an example. Let's say we have an app for restaurant menu and we want to download fresh menu everyday before the dinner (I don't know when you eat the dinner, imagine people in our restaurant eat dinner between 3:00 PM and 6:00PM). So we need to download the menu everyday before 3:00 PM so the user could see immediately what's today. E.g. we want to schedule DownloadMenuWorker everyday between 09:00 AM and 12:00 PM (menu to our server database is added everyday in the morning and we want 3 hours buffer before dinner time starts). Here's code that enqueue appropriate Worker:

val request = PeriodicWorkRequestBuilder<DownloadMenuWorker>(
    repeatInterval = Duration.ofHours(24),
    flexTimeInterval = Duration.ofHours(3)
).apply {
    setInitialDelay(calculateNext12PM())
}.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
    UNIQUE_WORK_NAME
    ExistingPeriodicWorkPolicy.KEEP,
    request
)

If I understand correctly, it should delay the first run to the next 12 PM, and after that it should run periodically everyday between 09:00 AM and 12:00 PM (because of repeatInterval = 24 hours and flexTimeInterval = 3 hours). Now my questions is, what if the x time run the real start of the Worker will be 12:24 PM because of the inexactness of periodic requests? The next 24 hours for the x+1 time run will count from 12:24 PM or from 12:00 PM? If it counts from 12:24 PM does it mean that x + 100 run can be completely different than original assumptions (between 9:00 AM and 12:00 PM) and our guests will have fresh menu when dinner time has finished?

In other words, which of the following visualizations is correct?

1. 1

2. 2

The second case will cause that the delay and inexactness will expand over many days.

question from:https://stackoverflow.com/questions/66059663/how-periodic-work-works-with-workmanager

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...