TheHeuman
TheHeuman

Reputation: 178

WorkManager PeriodicWorkRequest run twice

I have an app that runs a database refresh every 15 mins.

The PeriodicWorkRequest is enqueued in onCreate of my main activity.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    updateDatabasePeriodically();


public void updateDatabasePeriodically() {
    PeriodicWorkRequest updateDatabaseRequest =
            new PeriodicWorkRequest.Builder(UpdateDatabaseWorker.class, 15, TimeUnit.MINUTES).build();

    WorkManager.getInstance(getMainActivityContext()).enqueue(updateDatabaseRequest);
}

UpdateDatabaseWorker:

@Override
public Result doWork() {
    // Do the work here--in this case, upload the images.


    updateDatabase();
    // Indicate whether the task finished successfully with the Result
    return Result.success();
}

private void updateDatabase() {
    AppDatabase appDatabase = AppDatabase.getInstance(context);

    Log.i(TAG, "Updating alerts at: " + DateTimeHelper.getHumanReadableTime(now));
}

The problem is that the work is done twice every time the job executes as can be seen by my log statements

2019-11-22 10:20:23.185 24987-25085/com.package.myapp I/com.package.myapp.UpdateDatabaseWorker: Updating at: 22/11/2019 10:20:23
2019-11-22 10:21:30.510 25309-25408/com.package.myapp I/com.package.myapp.UpdateDatabaseWorker: Updating at: 22/11/2019 10:21:30

2019-11-22 10:34:49.642 25309-26180/com.package.myapp I/com.package.myapp.UpdateDatabaseWorker: Updating at: 22/11/2019 10:34:49
2019-11-22 10:35:23.372 25309-26198/com.package.myapp I/com.package.myapp.UpdateDatabaseWorker: Updating at: 22/11/2019 10:35:23

Why is this happening? Should I be creating the request somewhere else?

Would this be a good solution? https://stackoverflow.com/a/53059601/9137086

I feel like that's a treating the symptom instead of the disease

Upvotes: 2

Views: 1989

Answers (1)

pfmaggi
pfmaggi

Reputation: 6496

In this cases please, use an uniqueWorkRequest, otherwise (especially for PeriodicWorkRequest) you will end up with duplicates.

public void updateDatabasePeriodically() {
    PeriodicWorkRequest updateDatabaseRequest =
            new PeriodicWorkRequest.Builder(UpdateDatabaseWorker.class, 15, TimeUnit.MINUTES).build();

    WorkManager.getInstance(getMainActivityContext())
        .enqueueUniquePeriodicWork("uniqueWorkName", 
                           ExistingPeriodicWorkPolicy.KEEP,
                           updateDatabaseRequest);
}

You can take a look at the reference for WorkManager#enqueueUniqueWork for more information on the call and on the ExistingPeriodicWorkPolicy one to see which are the options.

If you don't have requirements to use REPLACE, please use KEEP, it's less expensive and avoid stopping an already working Work.

Upvotes: 11

Related Questions