I am trying to run an api call periodically every one hour. I know the minimum time interval for periodic request is 15 minutes i have definitely kept it more than that.
Below is my code to run periodic request
val data = Data.Builder().putString(
"covid_country",
viewModel?.getSavedCountry()
).build()
val request =
PeriodicWorkRequest.Builder(CovidWorker::class.java, 1, TimeUnit.HOURS)
.setInputData(data)
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.build()
WorkManager.getInstance(this)
.enqueueUniquePeriodicWork("simplified", ExistingPeriodicWorkPolicy.KEEP, request)
In the workmanager
class's doWork
method i am just calling the api and send local notification if successfully.
override fun doWork(): Result {
val covidCountry = inputData.getString("covid_country")
Log.i("savedd112", covidCountry)
Coroutines.main {
val response =
CovidApi().getCovidCases("india")
val count = response?.get(response.size - 1)?.Cases ?: 0
Log.i("hereeached", "mark")
displayNotification("Cases in india", "$count")
}
return Result.retry()
}
But it is never runned. I dont see my local notification. I waited the whole day for this. There is no easy way to debug this so i decided to convert my periodic work request to one time work request and added a button in my UI
and on the button on click listener i called the following code
WorkManager.getInstance(this).enqueue(request)
Now the api gets called correctly and the local notification is displayed when the api
succeeds. I dont understand why my periodic request is not running
So i finally figured it out
Instead of using
ExistingPeriodicWorkPolicy.KEEP
use this
ExistingPeriodicWorkPolicy.REPLACE