Search code examples
androidandroid-jetpackandroid-workmanager

Check if WorkRequest has been previously enquequed by WorkManager Android


I am using PeriodicWorkRequest to perform a task for me every 15 minutes. I would like to check, if this periodic work request has been previously scheduled. If not, schedule it.

     if (!PreviouslyScheduled) {
        PeriodicWorkRequest dataupdate = new PeriodicWorkRequest.Builder( DataUpdateWorker.class , 15 , TimeUnit.MINUTES).build();
        WorkManager.getInstance().enqueue(dataupdate);
      }

Previously when I was performing task using JobScheduler, I used to use

public static boolean isJobServiceScheduled(Context context, int JOB_ID ) {
    JobScheduler scheduler = (JobScheduler) context.getSystemService( Context.JOB_SCHEDULER_SERVICE ) ;

    boolean hasBeenScheduled = false ;

    for ( JobInfo jobInfo : scheduler.getAllPendingJobs() ) {
        if ( jobInfo.getId() == JOB_ID ) {
            hasBeenScheduled = true ;
            break ;
        }
    }

    return hasBeenScheduled ;
}

Need help constructing a similar module for work request to help find scheduled/active workrequests.


Solution

  • Set some Tag to your PeriodicWorkRequest task:

        PeriodicWorkRequest work =
                new PeriodicWorkRequest.Builder(DataUpdateWorker.class, 15, TimeUnit.MINUTES)
                        .addTag(TAG)
                        .build();
    

    Then check for tasks with the TAG before enqueue() work:

        WorkManager wm = WorkManager.getInstance();
        ListenableFuture<List<WorkStatus>> future = wm.getStatusesByTag(TAG);
        List<WorkStatus> list = future.get();
        // start only if no such tasks present
        if((list == null) || (list.size() == 0)){
            // shedule the task
            wm.enqueue(work);
        } else {
            // this periodic task has been previously scheduled
        }
    

    But if you dont really need to know that it was previously scheduled or not, you could use:

        static final String TASK_ID = "data_update"; // some unique string id for the task
        PeriodicWorkRequest work =
                new PeriodicWorkRequest.Builder(DataUpdateWorker.class,
                        15, TimeUnit.MINUTES)
                        .build();
    
        WorkManager.getInstance().enqueueUniquePeriodicWork(TASK_ID,
                    ExistingPeriodicWorkPolicy.KEEP, work);
    

    ExistingPeriodicWorkPolicy.KEEP means that the task will be scheduled only once and then work periodically even after device reboot. In case you need to re-schedule the task (for example in case you need to change some parameters of the task), you will need to use ExistingPeriodicWorkPolicy.REPLACE here