WorkManager - remove periodic worker for good
Asked Answered
C

2

6

I had an update with the following code that adds a new periodic worker every three hours.

fun runCouponValidatorWorker() {
    val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
    val worker = PeriodicWorkRequestBuilder<CouponValidatorWorker>(3, TimeUnit.HOURS).setConstraints(constraints).build()
    WorkManager.getInstance()?.enqueueUniquePeriodicWork("couponValidatorWorker", ExistingPeriodicWorkPolicy.REPLACE, worker)
}

I'd like to release an update that will "kill" this worker and every scheduled instance of this worker.

What would be the best way to do that?

Cropdusting answered 22/7, 2018 at 12:21 Comment(0)
I
7

Did you try simply calling this:

WorkManager.getInstance(context).cancelUniqueWork("couponValidatorWorker")
Intestinal answered 22/7, 2018 at 12:39 Comment(6)
It wasn't clear from the documentation whether it cancels the current worker(named "couponValidatorWorker") if exists/running right now, or cancel any periodical occurrence of it. Will it cancel any other scheduled worker of it?Cropdusting
the docs specifically state: "Note that cancellation is a best-effort policy and work that is already executing may continue to run." In other words it will cancel all future and ATTEMPT to cancel already running tasks, but no guarantees. developer.android.com/reference/androidx/work/…Intestinal
All workers with this identifier ("couponValidatorWorker") will be cancelledIntestinal
Got it. Thanks.Cropdusting
I don't think this is correct (anymore?). Looking at the code in WorkManagerImpl it seems to allow rescheduling of the worker.Upwards
The documention does not say "cancel all future work". It says: Cancels all unfinished work in the work chain with the given name. So this is probably not the solution.Wende
B
3
WorkManager.getInstance().cancelAllWorkByTag(TAG)
Beatify answered 27/1, 2021 at 5:45 Comment(1)
While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Lamellirostral

© 2022 - 2024 — McMap. All rights reserved.