Android version: 8.1.0
Device: Infinix X604B
Workmanager: 1.0.0-alpha11 (latest version)
Scheduled a PeriodicWorkRequest to run after every 15 minutes. Work request runs after every 15 minutes for approximately one hour. Then PeriodicWorkRequest stops working. In 8 hours the background work doesn't get scheduled at all. I have not killed my app, it is in the background.
When I bring the app back to foreground PeriodicWorkRequest runs the background task again. With similar experience no repetition after I put my app in the background.
I've disabled battery optimization for my app.
Here is My Worker class sample.
class TestWorker extends Worker {
public TestWorker(
@NonNull Context context,
@NonNull WorkerParameters params) {
super(context, params);
}
@NonNull
@Override
public Result doWork() {
// Adding timestamp of background execution to firestore.
Map<String, String> value = new TreeMap<>();
SimpleDateFormat df = new SimpleDateFormat("hh:mm");
String dateFormat = df.format(Calendar.getInstance().getTime());
value.put("time", dateFormat);
FirebaseFirestore.getInstance()
.collection("my-collection")
.add(value);
return Result.SUCCESS;
}
}
This is how I call it:
PeriodicWorkRequest.Builder testBuilder =
new PeriodicWorkRequest.Builder(TestWorker.class, 15,
TimeUnit.MINUTES);
PeriodicWorkRequest testWork = testBuilder.build();
WorkManager.getInstance().enqueue(testWork);
You can begin with unique periodic work like below,
WorkManager.getInstance().enqueueUniquePeriodicWork(UNIQUE_ID, ExistingPeriodicWorkPolicy.REPLACE, testWork);
Here, UNIQUE_ID
is String that will check for uniqueness of your worker and replace existing one if it's already exists in queue for periodic work.
Check out Worker policies here.
And don't forget to add the same tag to your worker instance like:
PeriodicWorkRequest.Builder testBuilder =
new PeriodicWorkRequest.Builder(TestWorker.class, 15, TimeUnit.MINUTES);
PeriodicWorkRequest testWork = testBuilder.addTag(UNIQUE_ID).build(); // Set the same string tag for worker.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With