Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Periodic work requests with WorkManager not working

  • I am using Workmanager to execute a task within a time period of minutes but it gets executed for the first time only. From my point of view it should execute every minutes.
  • I am testing on device while the app is in foreground running and power is on.

Code:

class MainActivity : AppCompatActivity() {

    val TAG: String = "MainActivity"
    lateinit var workLiveData: LiveData<List<WorkInfo>>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initWM()
    }

    private fun initWM() {
        val request = PeriodicWorkRequestBuilder<DemoWorker>(1, TimeUnit.MINUTES)
        .addTag(TAG)
        .build()
    
    WorkManager.getInstance(this).enqueueUniquePeriodicWork(TAG, 
        ExistingPeriodicWorkPolicy.REPLACE, request)
    }
}

DemoWorker:

class DemoWorker(
    context: Context,
    params: WorkerParameters
) : Worker(context, params) {

    val TAG: String = "MainActivity"

    override fun doWork(): Result {
        Log.d(TAG, "doWork: ")
        return try {
            Result.success(workDataOf("KEY" to "SUCCESS"))
        } catch (e: Exception) {
            Result.failure()
        }
    }
}
like image 498
Sumit Shukla Avatar asked Dec 06 '25 02:12

Sumit Shukla


1 Answers

A reminder about the “minimal interval”. WorkManager is balancing two different requirements: the application with its WorkRequest, and the Android operating system with its need to limit battery consumption. For this reason, even if all the constraints set on a WorkRequest are satisfied, your Work can still be run with some additional delay.

So you are replacing one work after another. The OS may not have the proper time to execute the work. So the best option will be to try with a 1-hour delay.

You can use a flexInterval.Let’s look at an example. Imagine you want to build a periodic Work request with a 30 minutes period. You can specify a flexInterval, smaller than this period, say a 15 minute flexInterval. The actual code to build a PeriodicWorkPequest with this parameters is:

val logBuilder = PeriodicWorkRequestBuilder<MyWorker>(
                     30, TimeUnit.MINUTES, 
                     15, TimeUnit.MINUTES)

The result is that our worker will be executed in the second half of the period (the flexInterval is always positioned at the end of the repetition period):

like image 127
Amit Kundu Avatar answered Dec 08 '25 00:12

Amit Kundu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!