Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PeriodicWorkRequest with WorkManager

Well as WorkManager is newly introduce in Google I/O, I'm trying to use workmanager to perform task periodically,

What I'm doing is, Scheduling the work using PeriodicWorkRequest as following :

Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();
PeriodicWorkRequest build = new PeriodicWorkRequest.Builder(SyncJobWorker.class, MY_SCHEDULE_TIME, TimeUnit.MILLISECONDS)
           .addTag(TAG)
           .setConstraints(constraints)
           .build();

WorkManager instance = WorkManager.getInstance();
if (instance != null) {
          instance.enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.REPLACE, build);
}

Problem I'm having is when i'm requesting PeriodicWorkRequest then also it will start work immediately,

  • Does anybody know how to stop that immediate work execution? while using PeriodicWorkRequest.
  • Also want to know how we can Rechedule the work? What if i want to change the time of already scheduled work ?

I'm using : implementation "android.arch.work:work-runtime:1.0.0-alpha04"

Any help will be appreciated.

like image 364
Uttam Panchasara Avatar asked Jul 03 '18 11:07

Uttam Panchasara


People also ask

Can WorkManager be used to repeat jobs?

Retry and backoff policy If 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.

When would you use a WorkManager?

Use WorkManager for reliable work WorkManager is intended for work that is required to run reliably even if the user navigates off a screen, the app exits, or the device restarts. For example: Sending logs or analytics to backend services. Periodically syncing application data with a server.

Does WorkManager run on background thread?

Worker is the simplest implementation, and the one you have seen in previous sections. WorkManager automatically runs it on a background thread (that you can override).

What is difference between WorkManager and service?

WorkManager is not answer to all of the background tasks. E.G. You shouldn't use it for processing payments since it doesn't need to survive process death and these task needs to be executed immediately. Consider using Foreground Service. Its also not a great idea to use them for parsing data and contents of view.


2 Answers

You can achieve this by using flex period in PeriodicWorkRequest.Builder. As example, if you want run your Worker within 15 minutes at the end of repeat interval (let's say 8 hours), code will look like this:

val periodicRefreshRequest = PeriodicWorkRequest.Builder(
            RefreshWorker::class.java, // Your worker class
            8, // repeating interval
            TimeUnit.HOURS,
            15, // flex interval - worker will run somewhen within this period of time, but at the end of repeating interval
            TimeUnit.MINUTES
    )

Visual ilustration

like image 167
Myroslav Avatar answered Oct 22 '22 21:10

Myroslav


you need to add initialDelay to the builder

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

    val request: PeriodicWorkRequest = PeriodicWorkRequest.Builder(
        MySimpleWorker::class.java, 3, TimeUnit.HOURS, 1, TimeUnit.HOURS)
        .setConstraints(constraints)
        .setInitialDelay(2, TimeUnit.HOURS)
        .setBackoffCriteria(BackoffPolicy.LINEAR, 1, TimeUnit.HOURS)
        .build()
    mWorkManager.enqueueUniquePeriodicWork(
        TAG_WORK_NAME,
        ExistingPeriodicWorkPolicy.KEEP,
        request
    )
}
like image 30
Dan Alboteanu Avatar answered Oct 22 '22 20:10

Dan Alboteanu