Execute task every second using Work Manager API

Chivorn picture Chivorn · Jul 6, 2018 · Viewed 11.2k times · Source

Work Manager is a new API and I try to execute task every second, but it doesn't work.

This is my worker class

class TestingWorker : Worker(){
    override fun doWork(): Result {
        Log.i("CheckWorker","Result here")
        return Result.SUCCESS
    }
}

and this is where I called it.

 val recurringWork: PeriodicWorkRequest = PeriodicWorkRequest.Builder(TestingWorker::class.java, 1, TimeUnit.SECONDS).build()
 WorkManager.getInstance()?.enqueue(recurringWork)

Answer

Sagar picture Sagar · Jul 6, 2018

Its not working because, the minimum interval between two periodic work request is 15 min which is defined by MIN_PERIODIC_INTERVAL_MILLIS.

Based on the documentation:

Creates a PeriodicWorkRequest to run periodically once every interval period. The PeriodicWorkRequest is guaranteed to run exactly one time during this interval. The intervalMillis must be greater than or equal to PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS. It may run immediately, at the end of the period, or any time in between so long as the other conditions are satisfied at the time.

I would recommend you to avoid scheduling work so frequently. This will end up in consuming more resources and eventually impacting the battery life.