Periodic daily work requests using WorkManager
Solution 1
You can now use enqueueUniquePeriodicWork
method. It was added in 1.0.0-alpha03 release of the WorkManager.
Solution 2
You are looking for enqueueUniquePeriodicWork
This method allows you to enqueue a uniquely-named PeriodicWorkRequest, where only one PeriodicWorkRequest of a particular name can be active at a time. For example, you may only want one sync operation to be active. If there is one pending, you can choose to let it run or replace it with your new work.
Sample code
public static final String TAG_MY_WORK = "mywork";
public static void scheduleWork(String tag) {
PeriodicWorkRequest.Builder photoCheckBuilder =
new PeriodicWorkRequest.Builder(WorkManagerService.class, 1, TimeUnit.DAYS);
PeriodicWorkRequest request = photoCheckBuilder.build();
WorkManager.getInstance().enqueueUniquePeriodicWork(tag, ExistingPeriodicWorkPolicy.KEEP , request);
}
You get two types of ExistingPeriodicWorkPolicy
KEEP
If there is existing pending work with the same unique name, do nothing.
REPLACE
If there is existing pending work with the same unique name, cancel and delete it.
Solution 3
Eventually, I understood, that the problem lies in the way how the LiveData
is used. Because there are no observers, there is no value inside.
The problem with using just the PeriodicWork
is that it doesn't ensure the uniqueness of the work you want to do. In other words, it is possible to have many works that will be active simultaneously firing more times than you need.
![Gaket](https://i.stack.imgur.com/CGSNr.jpg?s=256&g=1)
Gaket
I am a passionate Android developer. Got Master of CS degree in Moscow Physics university, then graduated from Carnegie Mellon University program as a Master of Science in Information Technology
Updated on June 15, 2022Comments
-
Gaket about 2 years
How to properly use the new
WorkManager
from Android Jetpack to schedule a one per day periodic work that should do some action on a daily basis and exactly one time?The idea was to check if the work with a given tag already exists using
WorkManager
and to start a new periodic work otherwise.I've tried to do it using next approach:
public static final String CALL_INFO_WORKER = "Call worker"; ... WorkManager workManager = WorkManager.getInstance(); List<WorkStatus> value = workManager.getStatusesByTag(CALL_INFO_WORKER).getValue(); if (value == null) { WorkRequest callDataRequest = new PeriodicWorkRequest.Builder(CallInfoWorker.class, 24, TimeUnit.HOURS, 3, TimeUnit.HOURS) .addTag(CALL_INFO_WORKER) .build(); workManager.enqueue(callDataRequest); }
But the
value
is always null, even if I put a breakpoint inside theWorker
'sdoWork()
method (so it is definitely in progress) and check the work status from another thread.