WorkManager PeriodicWorkRequest运行两次

时间:2019-11-22 15:56:25

标签: android android-workmanager

我有一个应用程序,每15分钟运行一次数据库刷新。

PeriodicWorkRequest已排入我的主要活动的onCreate中。

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));
}

问题是,每次执行该工作都会完成两次,正如我的日志语句所示

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

为什么会这样?我应该在其他地方创建请求吗?

这将是一个好的解决方案吗? https://stackoverflow.com/a/53059601/9137086

我觉得那是治疗症状而不是疾病

1 个答案:

答案 0 :(得分:0)

在这种情况下,请使用uniqueWorkRequest,否则(特别是对于PeriodicWorkRequest),您将得到重复项。

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

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

您可以查看WorkManager#enqueueUniqueWork的参考,以获取有关通话和ExistingPeriodicWorkPolicy的更多信息,以了解哪些选项。

如果您没有使用REPLACE的要求,请使用KEEP,它便宜一些,并且避免停止已经可以工作的Work。