Android WorkManager api for running daily task in Background

lavanya velu picture lavanya velu · May 18, 2018 · Viewed 17.1k times · Source

I need to call one API daily in the background even if the app is closed. I have seen about WorkManager API. For my scenario, I tried PeriodicWorkRequest but unfortunately, it's not working as my expected result. What I did is I used this code in the Application class

 PeriodicWorkRequest.Builder myWorkBuilder =
                new PeriodicWorkRequest.Builder(MyWorker.class, 24,
                        TimeUnit.HOURS);

        PeriodicWorkRequest myWork = myWorkBuilder.build();
        WorkManager.getInstance().enqueue(myWork);

But it's running repeatedly for 11 times when the app is open for the first time after that, it's not running after 24 hrs. Please, anyone, help me to solve.

Answer

whlk picture whlk · Jun 28, 2018

If you want to make sure your PeriodicWorkRequest is not created multiple times you can use the WorkManager.enqueueUniquePeriodicWork method to schedule your worker:

This method allows you to enqueue a uniquely-named PeriodicWorkRequest, where only one PeriodicWorkRequest of a particular name can be active at a time. For example, you may only want one sync operation to be active. If there is one pending, you can choose to let it run or replace it with your new work.


For example:

PeriodicWorkRequest.Builder myWorkBuilder =
            new PeriodicWorkRequest.Builder(MyWorker.class, 24, TimeUnit.HOURS);

PeriodicWorkRequest myWork = myWorkBuilder.build();
WorkManager.getInstance()
    .enqueueUniquePeriodicWork("jobTag", ExistingPeriodicWorkPolicy.KEEP, myWork);