Search code examples
androidandroid-studioandroid-workmanager

Override Deadline for Work Manager (Android Studio)


Now that Work Manager is replacing Job Scheduler, I was trying to figure out how to set an Override Deadline for Work Manager using a OneTimeWorkRequest, as we did in Job Scheduler. I tried looking through the set of constraints, but was unable to find an equivalent. I also looked through the options in OneTimeWorkRequest.Builder, but once again found nothing. How would I go about setting an override deadline?


Solution

  • setOverrideDeadline, as per its documentation, causes your job to run even if your other constraints are not met. WorkManager does not do that: it always respects your constraints.

    You can, of course, enqueue a second work request using setInitialDelay to the time you want as your 'override deadline', not including your other constraints and including a specific tag.

    That would mean you'd have two enqueue workers:

    1. The real worker, with constraints and a tag, say "real_work"
    2. The override deadline worker, with no constraints, an intial delay, and a tag, say "override"

    If the real worker fires, you can call workManager.cancelAllWorkByTag("override") to cancel your override deadline worker and proceed as normal.

    If your override deadline worker fires, that means that there was no time between when you enqueued your workers and the override deadline. Here is where you'd want to figure out your alternative strategy (such as re-enqueuing a new worker with less constraints, etc.). It is also where you'd want to workManager.cancelAllWorkByTag("real_work") if you want your real work be canceled.