Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set initial delay to a Periodic Work Manager in Android

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?

like image 982
Sriram R Avatar asked Aug 21 '18 09:08

Sriram R


People also ask

What is WorkManager in Android?

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.

How do I run a WorkManager at a certain time?

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.

Which API do you use to add constraints to a WorkRequest?

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

What is OneTimeWorkRequest?

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 .


Video Answer


1 Answers

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);
like image 186
Anjal Saneen Avatar answered Sep 28 '22 00:09

Anjal Saneen