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.
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.
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.
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.
Is there any way to do this with just the PeriodicWorkRequest
API?
WorkManager is intended for work that is required to run reliably even if the user navigates off a screen, the app exits, or the device restarts. For example: Sending logs or analytics to backend services. Periodically syncing application data with a server.
You can schedule a work, with onetime initial delay or execute it periodically, using the WorkManager as follows: Create Worker class: public class MyWorker extends Worker { @Override public Worker. WorkerResult doWork() { // Do the work here // Indicate success or failure with your return value: return WorkerResult.
To create a set of constraints and associate it with some work, create a Constraints instance using the Contraints. Builder() and assign it to your WorkRequest. Builder() .
androidx.work.OneTimeWorkRequest. A WorkRequest for non-repeating work. OneTimeWorkRequests can be put in simple or complex graphs of work by using methods like WorkManager. beginWith or WorkManager. beginWith .
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.
Example:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With