PeriodicWorkRequest with WorkManager

Uttam Panchasara picture Uttam Panchasara · Jul 3, 2018 · Viewed 10k times · Source

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.

Answer

Myroslav Kolodii picture Myroslav Kolodii · Nov 23, 2018

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