Can the WorkManager's behavior after reboots be customized?

Viewed 268

I am exploring the option of using WorkManager for some of my usecases where a work item needs to be executed after a scheduled delay. Based on experimentation, I noticed this behavior

  1. WorkManager gracefully handles scheduling of work items and respects the configured delay even after a reboot as long as the delay has not elapsed when the device is shutdown.
  2. If the delay for certain work items has elapsed when the device is in shutdown state, WorkManager eventually acts on all such work items at the same time (delay is no longer respected) once the device is rebooted.

Is what I am observing the expected behavior? If so , Is there a way to customize the behavior in 2 above? Basically, I am asking if the same delay can be respected after reboot. Potentially , this could be done with saving some state so that the work items that have elapsed delay can be differentiated, but wanted to check if WorkManager itself provides interfaces to customize this behavior.

For reference, Here's how I am initializing the WorkManager and scheduling work after a set delay (5 minutes in this example)

OneTimeWorkRequest workItem =
                new OneTimeWorkRequest.Builder(MyWork.class)
                .setInitialDelay(30000, TimeUnit.MILLISECONDS)
                .build();

WorkManager.getInstance()
                .beginUniqueWork(<some_id>,
                ExistingWorkPolicy.KEEP,
                workItem)
                .enqueue();
1 Answers

WorkManager doesn't provide such facility. The only info you can get from a Worker are its state (ENQUEUED, RUNNING, SUCCEEDED, FAILED, BLOCKED, CANCELLED), runAttemptCount and output. You will need to implement it by yourself. Save in SharedPreferences the time when your worker ends. And check this time when the device reboot and eventually re-enqueue your worker with ExistingWorkPolicy.REPLACE

Related