3

For OneTimeWorkRequest we can use WorkContinuation to ensure that if the job is already scheduled we can KEEP or REPLACE it. There is no such option for PeriodicWorkRequest, so every time my main activity is created a new job is created and after a while I get this exception.

java.lang.IllegalStateException: Apps may not schedule more than 100 distinct jobs

So I'm trying the following to create a "unique peiodic work"

public void schedule(){
    Constraints constraints = new Constraints.Builder().setRequiresBatteryNotLow(true).build();
    OneTimeWorkRequest zombieSpawnWorker = new OneTimeWorkRequest.Builder(ZombieSpawnWorker
            .class).setInitialDelay(15, TimeUnit.MINUTES).setConstraints(constraints).addTag(ZombieSpawnWorker.TAG).build();
    this.setUuid(zombieSpawnWorker.getId());
    WorkManager.getInstance().beginUniqueWork(TAG,
                    ExistingWorkPolicy.KEEP,
                    OneTimeWorkRequest.from(ZombieSpawnWorker.class));
}

And then calling this method again at the end of the work

public WorkerResult doWork() {
    try {
        //work to be done
    } catch (Exception e) {
        Log.e(TAG,e.getLocalizedMessage());
        return WorkerResult.FAILURE;
    }
    schedule();
    return WorkerResult.SUCCESS;
}
Sila Siebert
  • 422
  • 4
  • 10

2 Answers2

5

Another workaround is to add a tag REQUEST_TAG to the PeriodicWorkRequestBuilder, and then call WorkManager.getInstance().cancelAllWorkByTag(REQUEST_TAG) before you enqueue the periodic request.

Joe H
  • 71
  • 2
1

The IllegalStateException you see was a bug we fixed in alpha01. Use the alpha02 library, and you won't see that problem. For more information, take a look at the release notes here.

Rahul
  • 19,744
  • 1
  • 25
  • 29
  • Thank you. We had updated to alpha02 and observe it again. May I know, for one time worker, at the end of its execution, do we need to explicitly cancel tag, to avoid this kind of problem? – Cheok Yan Cheng Jun 02 '18 at 10:02
  • Also, we are using WorkManager to perform alarm reminder scheduling. Having limitation "Apps may not schedule more than 100 distinct jobs", does that means `WorkManager` is not suitable to schedule more than 100 reminders? – Cheok Yan Cheng Jun 02 '18 at 13:36
  • @CheokYanCheng Have you found any solution for more than 100 job exception. – Sujeet Kumar Jun 14 '19 at 09:48