Search code examples
androidandroid-jobschedulerandroid-jetpackandroid-workmanager

WorkManager adding too many jobs to JobScheduler


I'm trying to schedule a task to run at a specific time using WorkManager. I'm using beginUniqueWork as I want only one task scheduled at a time for that specific ID (uniqueWorkName). But after calling enqueue multiple times, at some point I get the following error:

java.lang.IllegalStateException: Apps may not schedule more than 100 distinct jobs
    at android.os.Parcel.readException(Parcel.java:2012)
    at android.os.Parcel.readException(Parcel.java:1950)
    at android.app.job.IJobScheduler$Stub$Proxy.schedule(IJobScheduler.java:180)
    at android.app.JobSchedulerImpl.schedule(JobSchedulerImpl.java:44)
    at androidx.work.impl.background.systemjob.SystemJobScheduler.scheduleInternal(SystemJobScheduler.java:85)
    at androidx.work.impl.background.systemjob.SystemJobScheduler.schedule(SystemJobScheduler.java:64)
    at androidx.work.impl.Schedulers.scheduleInternal(Schedulers.java:98)
    at androidx.work.impl.Schedulers.schedule(Schedulers.java:69)
    at androidx.work.impl.WorkManagerImpl.rescheduleEligibleWork(WorkManagerImpl.java:398)
    at androidx.work.impl.utils.ForceStopRunnable.run(ForceStopRunnable.java:66)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
    at java.lang.Thread.run(Thread.java:764)

When I log the number of pending jobs using the following snippet after every enqueue, I noticed that there are 3 new jobs added to the list for every call (while I expect the total to stay at 1).

JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
int size = jobScheduler.getAllPendingJobs().size();

Here is the code I'm using to schedule tasks:

val work = OneTimeWorkRequest.Builder(workerClass)
        .setInitialDelay(offset, TimeUnit.MILLISECONDS)
        .build()
WorkManager.getInstance()
        .beginUniqueWork(uniqueNameForTask, ExistingWorkPolicy.REPLACE, work)
        .enqueue()

Does anything look off here? What am I missing? 🤔


Solution

  • As per the WorkManager 1.0.0-alpha07 release notes, one of the fixes for 1.0.0-alpha07 was:

    Work that has finished execution now correctly cancels all pending copies of that work in other Schedulers. This led to exceeding the JobScheduler jobs limit. b/111569265

    So upgrading to 1.0.0-alpha07 should fix your issue.