I want to start a Worker
that performs some task, and in case of error tries again after some delay with exponential backoff strategy.
Here is simplified Worker
for the sake of brevity:
class TestWorker(
context: Context,
workerParameters: WorkerParameters
) : Worker(
context,
workerParameters
) {
override fun doWork(): Result {
Log.d("DEBUG", "Attempt $runAttemptCount")
return Result.retry()
}
}
And this is how I schedule this Worker
:
class MainActivity : AppCompatActivity() {
private val TAG = "WORKER_TAG"
private val BACKOFF_DELAY_SECONDS = 60L
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val workManager = WorkManager.getInstance()
workManager.cancelAllWork()
val workRequest = OneTimeWorkRequest.Builder(TestWorker::class.java)
.setConstraints(
Constraints
.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.setBackoffCriteria(
BackoffPolicy.EXPONENTIAL,
BACKOFF_DELAY_SECONDS,
TimeUnit.SECONDS
)
.addTag(TAG)
.build()
workManager.enqueue(workRequest)
}
}
It works great on the majority of the devices, however I observe weird behaviour on some devices.
I expect Attempt 2 to be executed after 1 minute, but on Samsung J1, 6.0.1 I see the following log:
01-15 12:39:57.438 28396-28435/test.ru.workerissue D/DEBUG: Attempt 0
01-15 12:39:58.349 28396-28439/test.ru.workerissue D/DEBUG: Attempt 1
01-15 12:39:58.389 28396-28440/test.ru.workerissue D/DEBUG: Attempt 2
01-15 12:40:59.669 28396-28435/test.ru.workerissue D/DEBUG: Attempt 3
01-15 12:40:59.719 28396-28439/test.ru.workerissue D/DEBUG: Attempt 4
As you can see, the delay between all attempts except 2 and 3 is about 1 second.
If I run the same code on Nexus 6X, 8.1, I observe two attempts fired on startup simultaniously, and then everyting works as expected:
2019-01-15 13:01:06.610 28806-28841/test.ru.workerissue D/DEBUG: Attempt 0
2019-01-15 13:01:06.658 28806-28842/test.ru.workerissue D/DEBUG: Attempt 1
2019-01-15 13:02:06.747 28806-28975/test.ru.workerissue D/DEBUG: Attempt 2
2019-01-15 13:04:06.876 28806-29024/test.ru.workerissue D/DEBUG: Attempt 3
Also, I tested this on several other devices: Samsung Galaxy J3 - 8.0, Google Pixel XL - 8.1, Samsung Galaxy J1 - 5.1.1. Works as expected on all of these devices.
The version of WorkManager
is 1.0.0-beta01
What could be the reason of such inconsistency? Is it possible to fix it?
I created the issue and it should be fixed in the next release of WorkManager
: https://issuetracker.google.com/issues/122881597