This question has been asked many times in different forms but I am not getting it right and are wondering if it might not be an android bug.
After setting up WorkManager doWork() is called at random times and sometimes up to 10+ times in quick succession.
- It is called only once in my MainApplication (*see point below)
- If it is called unexpectedly I try clearing and restarting it
- I have uninstalled and re-installed the App
- I clear all instances prior to calling WorkManager
- I have tried creating it with a unique tag
The expected behaviour is a call once every 10-15 minutes
Please see details below: Implemented on LG K22 using Android studio Bumblebee 2021.1.1 Patch 2
Gradle Implementation:
implementation 'androidx.work:work-runtime-ktx:2.7.1'
MainActivity Code:
WorkManager.getInstance(this).cancelAllWorkByTag("scanDevices")
val myMonitorWorkerRequest = PeriodicWorkRequest.Builder(myMonitorWorker::class.java,
15, TimeUnit.MINUTES,5, TimeUnit.MINUTES).build()
WorkManager.getInstance(this)
.enqueueUniquePeriodicWork(
"scanDevices",
ExistingPeriodicWorkPolicy.KEEP,
myMonitorWorkerRequest)
- note: ExistingPeriodicWorkPolicy.REPLACE does not change the behavior here
Original Worker Class:
override fun doWork(): Result {
try{
runNotificationService()
return Result.success()
}
catch (e:Exception){
return Result.failure()
}
}
Current Worker Class:
override fun doWork(): Result {
try{
val timeNow = System.currentTimeMillis()
if(timeNow < lastTime+600000){
WorkManager.getInstance(theContext).cancelAllWorkByTag("scanDevices")
val myMonitorWorkerRequest = PeriodicWorkRequest.Builder(myMonitorWorker::class.java,
15, TimeUnit.MINUTES,5, TimeUnit.MINUTES).build()
WorkManager.getInstance(theContext)
.enqueueUniquePeriodicWork(
"scanDevices",
ExistingPeriodicWorkPolicy.KEEP,
myMonitorWorkerRequest)
}
else{
runNotificationService()
lastTime = timeNow
}
return Result.success()
}
catch (e:Exception){
return Result.failure()
}
}
The above code is not bulletproof yet since the worker class is called in such rapid succession sometimes, that multiple (instances / threads (I think)) are started at the same time and the updating of the global variables had not taken effect yet prior to another instance starting. It does dramatically reduce the number of calls though to only one or two additional instances slipping through.
Specifically, my question is, does anyone know if anything I am doing is either wrong or alternatively if there is a known bug report for multiple worker instances/threads being created?
See these similar references that I have tried but did not work:
WorkManager executing enqueueUniquePeriodicWork() multiple times at once?
doWork() for WorkManager called multiple times for OneTimeWorkRequest
*App Inspection shows 20 instances enqueued on android studio