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.
PeriodicWorkRequest for such tasks that need to execute periodically.
Here is how you can create a PeriodicWorkRequest:
val constraints = Constraints.Builder() .setRequiresCharging(true) .build() val saveRequest = PeriodicWorkRequestBuilder<SaveImageToFileWorker>(1, TimeUnit.HOURS) .setConstraints(constraints) .build() WorkManager.getInstance(myContext) .enqueue(saveRequest)
Constraints constraints = new Constraints.Builder() .setRequiresCharging(true) .build(); PeriodicWorkRequest saveRequest = new PeriodicWorkRequest.Builder(SaveImageFileWorker.class, 1, TimeUnit.HOURS) .setConstraints(constraints) .build(); WorkManager.getInstance(myContext) .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.
You can observe the status of PeriodicWorkRequests the same way as OneTimeWorkRequests. Read more about observing work.