what is the optimal way to run background operation multiple times on different sets of data with only one instance running in the background?
Asked
Active
Viewed 122 times
1
-
2Welcome to Stack Overflow! Use formatting tools to make your post more readable. Code block should look like `code block`. Use **bold** *italics* if needed. – Morse Jun 07 '18 at 02:44
-
Create a service and use Firebase JobDispatcher to execute that server at some point in time, or when some conditions are met. – MohammadL Jun 07 '18 at 02:51
1 Answers
3
You can make use of WorkManager architecture component to achieve it. Schedule a PeriodicWorkRequest
as follows:
Create Worker class:
public class MyWorker extends Worker {
@Override
public Worker.WorkerResult doWork() {
// Do the work here
// Indicate success or failure with your return value:
return WorkerResult.SUCCESS;
// (Returning RETRY tells WorkManager to try this task again
// later; FAILURE says not to try again.)
}
}
Schedule the Work:
PeriodicWorkRequest periodicWork = new
PeriodicWorkRequest.Builder(MyWorker.class, 12, TimeUnit.HOURS)
.build();
WorkManager.getInstance().enqueue(periodicWork);
This creates a PeriodicWorkRequest to run periodically once every 12 hours.
You can check out my answer on SO which describes if WorkManager is appropriate for your use-case.
The minimum supported API is 14.
Based on the documentation:
- WorkManger uses JobScheduler for API 23+
For API 14-22
- If using Firebase JobDispatcher in the app and the optional Firebase dependency, uses Firebase JobDispatcher
- Otherwise, uses a custom AlarmManager + BroadcastReceiver implementation

Sagar
- 23,903
- 4
- 62
- 62