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
You can use this following method :
enqueueUniquePeriodicWork()
, and implement like that :Please notice that the second parameter is the key. The enum can be
KEEP
orREPLACE
I think i am late to answer this question and you might have tweaked it too.. But i am trying to help anyways..
Explanation :
Everyone will be shocked if i will say :
Yes it results in data loss many times..
Yes, Prefer using
IntentService
.If a
intentservice
is already running and even ifthousands
of times it gets called... Then in that case too... all calls are kept inqueue
by android and processedone by one
andone after another
and after one isfinished
then only another waitingawakes
and starts to execute itHope it helps.