Tuesday, 6 October 2020

PeriodicWork with enqueueUniquePeriodicWork doesn't work

I'm trying to use WorkManger by creating a periodic Worker that repeats once every 5 days.

I am using version 1.0.0 of workmanagers on a Huawei Android 7 device (API 24)

android.arch.work:work-runtime:1.0.0

This is the code:

fun schedule() {
    val constraints: Constraints = Constraints.Builder().apply {
        setRequiredNetworkType(NetworkType.CONNECTED)
    }.build()

    val request = PeriodicWorkRequest
            .Builder(MyWorker::class.java, 5, TimeUnit.DAYS)
            .setConstraints(constraints)
            .build()

    WorkManager.getInstance()
            .enqueueUniquePeriodicWork(MyWorker.TAG, ExistingPeriodicWorkPolicy.KEEP, request)
}

MyWorker:

class MyWorker(appContext: Context, workerParams: WorkerParameters)
    : Worker(appContext, workerParams) {

    override fun doWork(): Result {
        return try {
            Thread.sleep(5000)
            Timber.i("success")
            Result.success()
        } catch (e: Exception) {
            Timber.e(e, "error")
            Result.failure()
        }
    }

The method schedule() is called in the onCreate() of the MainActivity.

When I install the app for the first time, the Worker runs only once. Also in the logs I see this error: CancellationException task was canceled

What am I doing wrong? Thanks.



from PeriodicWork with enqueueUniquePeriodicWork doesn't work

No comments:

Post a Comment