In the previous article we discussed the One Time Workers, and the basics of WorkManager. In this tutorial we'll see how to create PeriodicWorkerRequest. We'll use the same project which is used in the previous part of this tutorial.
To use a Worker periodically, you have to create a PeriodicWorkerRequest instead of OneTimeWorkerRequest.
PeriodicWorkRequest saveRequest =
new PeriodicWorkRequest.Builder(UpdateDataWorker.class, 4, TimeUnit.HOURS).build();
WorkManager.getInstance().enqueue(saveRequest);
new PeriodicWorkRequest.Builder(UpdateDataWorker.class, 4, TimeUnit.HOURS).build();
WorkManager.getInstance().enqueue(saveRequest);
This'll add the job to the worker queue, but every time the code runs, the Worker will be added to the queue. Let's talk about unique work requests!
Uniqueness
If you define a long running job, you have to prepare your application to the situation when a user navigates to another part of the app, like to another Activity, Fragment, and so on. And it may happen, that your previously defined WorkerRequest added to the WorkManager queue again, although you don't want it, so it'll run twice. To make a WorkerRequest unique, replace the enqueue() method to enqueueUniqueWork(), like this:
PeriodicWorkRequest uploadWorkRequest =
new PeriodicWorkRequest.Builder(UpdateDataWorker.class, 15, TimeUnit.MINUTES).addTag(Constants.WORKER_CHECKDATA).build();
WorkManager.getInstance()
.enqueueUniquePeriodicWork(Constants.WORKER_CHECKDATA, ExistingPeriodicWorkPolicy.KEEP, uploadWorkRequest);
We should talk about the ExistingPeriodicWorkPolicy parameter, because it's an important part of the method.It has to variables: KEEP and REPLACE. When KEEP is used, the WorkManager keeps the existing, running job, and skips the new. In case of REPLACE, the WM will cancel and delete the existing one, and enqueue the new.
Constraints
Now let's talk about constraints, which is a useful parts of the periodic workers. With constraints you can tell the WorkManager in which cases should the Worker run. For example, if your Worker downloads a file from the internet, you can set the WorkerRequest with the setRequiredNetworkType() method:
Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();PeriodicWorkRequest uploadWorkRequest = new PeriodicWorkRequest.Builder(UpdateDataWorker.class, 15, TimeUnit.MINUTES).setConstraints(constraints)
.addTag(Constants.WORKER_CHECKDATA).build();WorkManager.getInstance().enqueueUniquePeriodicWork(Constants.WORKER_CHECKDATA, ExistingPeriodicWorkPolicy.KEEP, uploadWorkRequest);
.addTag(Constants.WORKER_CHECKDATA).build();WorkManager.getInstance().enqueueUniquePeriodicWork(Constants.WORKER_CHECKDATA, ExistingPeriodicWorkPolicy.KEEP, uploadWorkRequest);
This Worker will runs only when the users mobile device has an active internet connection.