Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute task every second using Work Manager API

Tags:

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) 
like image 471
Chivorn Avatar asked Jul 06 '18 04:07

Chivorn


People also ask

Can WorkManager be used to repeat jobs?

Retry and backoff policyIf you require that WorkManager retry your work, you can return Result. retry() from your worker. Your work is then rescheduled according to a backoff delay and backoff policy. Backoff delay specifies the minimum amount of time to wait before retrying your work after the first attempt.

What's the best tool for handling work that is deferrable and expected to run even if your app restarts?

What is Work Manager? Work Manager is a library part of Android Jetpack which makes it easy to schedule deferrable, asynchronous tasks that are expected to run even if the app exits or device restarts i.e. even your app restarts due to any issue Work Manager makes sure the scheduled task executes again.

What is difference between JobScheduler and WorkManager in Android?

As mentioned in the previous section, WorkManager internally uses the JobScheduler API on Android 6.0 (API Level 23 – Marshmallow) and above devices. Therefore, there won't be any major differences between the WorkManager and JobScheduler on Android 6.0 and above devices. Both would behave in the same way.


1 Answers

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.

like image 118
Sagar Avatar answered Sep 25 '22 07:09

Sagar