I use the following code to schedule a background job execute every 15 mins.
WorkManager workManager = WorkManager.getInstance();
PeriodicWorkRequest ulpBackup;
ulpBackup = new PeriodicWorkRequest
.Builder(Ulp.class, 15, TimeUnit.MINUTES)
.addTag(activity.getString(R.string.job_tag))
.build();
workManager.enqueue(ulpBackup);
And here is the UlpBackup.class
public class UlpBackup extends Worker {
private Integer responseCounter = 0;
public UlpBackup() {}
@NonNull
@Override
public Result doWork() {
Log.d(logTag, "Starting periodic backup job";
final CountDownLatch countDownLatch = new CountDownLatch(1);
/** Read from local database and upload to firestore **/
localdb.setAPIListener(new APIListener() {
@Override
public void OnSuccess() {
responseCounter++;
if (responseCounter == 5) {
countDownLatch.countDown();
}
}
@Override
public void OnFailure() {
responseCounter++;
if (responseCounter == 5) {
countDownLatch.countDown();
}
}
});
localdb.sync();
try {
countDownLatch.await(300, TimeUnit.SECONDS);
} catch (Exception exception) {
Log.e(logTag, "Error in user list backup job " + exception.getMessage());
return Result.FAILURE;
}
Log.e(logTag, "Ulp backup completed");
return Result.SUCCESS;
}
The above code works fine and the job happened roughly every 15 minutes as expected. The only thing that I do not understand is that every time the job execute multiple times, can someone explain why and how can i avoid it?
From the log:
09-15 23:33:37.514 8190-8410: Starting periodic backup job
09-15 23:33:37.520 8190-8414: Starting periodic backup job
09-15 23:33:37.561 8190-8412: Starting periodic backup job
09-15 23:33:37.568 8190-8413: Starting periodic backup job
...
...
09-15 23:33:38.183 8190-8414: Ulp backup completed
09-15 23:33:39.164 8190-8412: Ulp backup completed
09-15 23:33:39.580 8190-8413: Ulp backup completed
09-15 23:38:37.517 8190-8410: Ulp backup completed