androidandroid-workmanagerandroid-jobscheduler

Android WorkManager: Is it possible to set task's maximum execution duration


I have a periodic task that requesting location updates on the background, but I need to restrict this task too work for a long period of time, as it will drain battery, so I need to stop it after a few minutes (3 min). Does Work Manager provide some mechanism to restrict the task's execution time ?


Solution

  • WorkManager doesn't have this functionality.
    There's a hard limit of 10 minutes when running a Worker and then the OS is going to stop the worker (this is possible to overcome promoting a Worker to a foreground service as described on the blog: Use WorkManager for immediate background execution).

    If you want to implement a timeout of 3 minutes you need to implement it in your worker.

    Using Kotlin and CoroutineWorker this can be implemented using withTimeout over the block of code that you want to run with a time limit:

    class MyWorker(
        appContext: Context,
        private val params: WorkerParameters
    ) : CoroutineWorker(appContext, params) {
    
      override suspend fun doWork(): Result {
        return withTimeout(3 * 60 * 1000) {
          // Do a long computation
          // ...
          return@withTimeout Result.success()
        }
      }
    }