Periodic daily work requests using WorkManager

前提是你 提交于 2019-11-30 19:35:49

You can now use enqueueUniquePeriodicWork method. It was added in 1.0.0-alpha03 release of the WorkManager.

You are looking for enqueueUniquePeriodicWork

This method allows you to enqueue a uniquely-named PeriodicWorkRequest, where only one PeriodicWorkRequest of a particular name can be active at a time. For example, you may only want one sync operation to be active. If there is one pending, you can choose to let it run or replace it with your new work.

Sample code

public static final String TAG_MY_WORK = "mywork";

public static void scheduleWork(String tag) {
    PeriodicWorkRequest.Builder photoCheckBuilder =
            new PeriodicWorkRequest.Builder(WorkManagerService.class, 1, TimeUnit.DAYS);
    PeriodicWorkRequest request = photoCheckBuilder.build();
    WorkManager.getInstance().enqueueUniquePeriodicWork(tag, ExistingPeriodicWorkPolicy.KEEP , request);
}

You get two types of ExistingPeriodicWorkPolicy

KEEP

If there is existing pending work with the same unique name, do nothing.

REPLACE

If there is existing pending work with the same unique name, cancel and delete it.

Eventually, I understood, that the problem lies in the way how the LiveData is used. Because there are no observers, there is no value inside.

The problem with using just the PeriodicWork is that it doesn't ensure the uniqueness of the work you want to do. In other words, it is possible to have many works that will be active simultaneously firing more times than you need.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!