Your application may at times require that certain tasks run periodically. For example, you may want to periodically backup your data, download fresh content in your app, or upload logs to a server.
Use the PeriodicWorkRequest
for such tasks that need to execute periodically.
PeriodicWorkRequest
cannot be chained. If your task requires chaining of tasks, consider OneTimeWorkRequest
.
Here is how you can create a PeriodicWorkRequest:
Constraints constraints = new Constraints.Builder()
.setRequiresCharging(true)
.build();
PeriodicWorkRequest saveRequest =
new PeriodicWorkRequest.Builder(SaveImageFileWorker.class, 1, TimeUnit.HOURS)
.setConstraints(constraints)
.build();
WorkManager.getInstance()
.enqueue(saveRequest);
The example showcases a periodic work request with a one hour repeat interval.
The repeat interval is defined as the minimum time between repetitions. The exact time that the worker is going to be executed depends on the constraints that you are using in your work request and on the optimizations done by the system.
In the example, the PeriodicWorkRequest also requires the device to be plugged in. In this case, even if the defined repeat interval of an hour passes, the PeriodicWorkRequest will run only when the device is plugged in.
Note: The minimum repeat interval that can be defined is 15 minutes (same as the JobScheduler API).
You can observe the status of PeriodicWorkRequests the same way as OneTimeWorkRequests. Read more about observing work.