Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AndroidX WorkManager - "how to" make a scheduled job persistent?

I have followed the guidelines from googles codelabs regarding the implementation of a WorkManager and scheduling of a job.

PeriodicWorkRequest workRequest =
                new PeriodicWorkRequest.Builder(Is30DaysOldWorker.class, PERIODIC_WORKREQUEST_INTERVAL, TimeUnit.SECONDS)
                                       .addTag(IS_30_DAYS_OLD_WORKER)
                                       .build();
getWorkManager().enqueue(workRequest);

From the google docs the WorkManager uses a JobScheduler for API 23+ (my case) - so is it possible make the scheduled job persistent after a device restart?

In a JobScheduler scenario you would normally do it by specifying a JobInfo.setPersisted(true) flag.

like image 870
daasen Avatar asked May 24 '18 13:05

daasen


1 Answers

I went through the documentation it is not mentioned that WorkManager will handle persisted WorkRequests although as you said that JobInfo already has that flag.

However in the source there is method named rescheduleEligibleWork(), which reschedules all jobs upon boot or similar cases. It stores the work requests in its own room database.

/**
     * Reschedules all the eligible work. Useful for cases like, app was force stopped or
     * BOOT_COMPLETED, TIMEZONE_CHANGED and TIME_SET for AlarmManager.
     *
     * @hide
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public void rescheduleEligibleWork() {
        // Reset scheduled state.
        getWorkDatabase().workSpecDao().resetScheduledState();

        // Delegate to the WorkManager's schedulers.
        // Using getters here so we can use from a mocked instance
        // of WorkManagerImpl.
        Schedulers.schedule(getWorkDatabase(), getSchedulers());
    }

There is no way specified how to configure it to act upon such cases in the doc. Since WorkManagerImpl constructor uses Context that (probably) means that if your application has permission to RECEIVE_BOOT_COMPLETED, the WorkManager will receive this event and reschedule all work requests that hasn't been executed within given window you have specified in the Work.Builder.

like image 149
Nikola Despotoski Avatar answered Oct 01 '22 18:10

Nikola Despotoski