Any way to have initial delay for PeriodicWorkRequest
Asked Answered
S

2

13

For OneTimeWorkRequest, we can have setInitialDelay to specific the initial delay.

However, there isn't such facility for PeriodicWorkRequest.

Is there any reliable way to achieve so?

One of the less reliable way, is to have a delayed OneTimeWorkRequest worker, to setup PeriodicWorkRequest. However, that's quite cumbersome, and create a possibility, where OneTimeWorkRequest may fail and not able to install PeriodicWorkRequest.

Saprophyte answered 8/7, 2018 at 7:38 Comment(1)
How did you fix this?Homonym
W
6

Since androidx.work:work-*:2.1.0, PeriodicWorkRequests support initial delays. You can use the setInitialDelay method on PeriodicWorkRequest.Builder to set an initial delay.

See link for official documentation.

Wivina answered 17/7, 2019 at 7:29 Comment(2)
setInitialDelay works weird. When I set a startup period of 15 minutes and the initial delay of 1 minute, the worker starts after 16 minutes. I thought it would immediately (as OneTimeWorkRequest), but after 1 minute (and not after 16 minutes). And the subsequent starts will be every 15 minutes.Cyclostyle
@Cyclostyle Looks like it executes at the end of the interval, not at the beginningStereophonic
S
5

Since the system runs your work you can't control the exact time it will run..

Your best option for creating a work execution delay is to use this PeriodicWorkRequest.Builder and supply a flexInterval as the 4th parameter:

PeriodicWorkRequest build = new PeriodicWorkRequest.Builder(
     SyncJobWorker.class, 
     REPEAT_INTERVAL, // repeatInterval
     TimeUnit.MILLISECONDS, // repeatIntervalTimeUnit
     FLEX_INTERVAL, // flexInterval
     TimeUnit.MILLISECONDS) // flexIntervalTimeUnit
       .build();

Docs ref: https://developer.android.com/reference/androidx/work/PeriodicWorkRequest.Builder#periodicworkrequestbuilder_2

Creates a PeriodicWorkRequest to run periodically once within the flex period of every interval period. See diagram below. The flex period begins at intervalMillis - flexMillis to the end of the interval. intervalMillis must be greater than or equal to PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS and flexMillis must be greater than or equal to PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS.

enter image description here

Sapiential answered 8/7, 2018 at 7:46 Comment(1)
Beware. Also from the docs: Note that flex intervals are ignored for certain OS versions (in particular, API 23). Also note that the minimum flex time, PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS, is 5 minutes.Greatest

© 2022 - 2024 — McMap. All rights reserved.