Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Workmanager PeriodicWorkRequest is not unique

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;
}
like image 353
Sila Siebert Avatar asked Nov 20 '25 15:11

Sila Siebert


1 Answers

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.

like image 71
Joe H Avatar answered Nov 24 '25 12:11

Joe H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!