Periodic daily work requests using WorkManager

我是研究僧i 提交于 2019-12-18 20:47:15

问题


How to properly use the new WorkManager from Android Jetpack to schedule a one per day periodic work that should do some action on a daily basis and exactly one time?

The idea was to check if the work with a given tag already exists using WorkManager and to start a new periodic work otherwise.

I've tried to do it using next approach:

public static final String CALL_INFO_WORKER = "Call worker";

...

WorkManager workManager = WorkManager.getInstance();
List<WorkStatus> value = workManager.getStatusesByTag(CALL_INFO_WORKER).getValue();
if (value == null) {
    WorkRequest callDataRequest = new PeriodicWorkRequest.Builder(CallInfoWorker.class,
                24, TimeUnit.HOURS, 3, TimeUnit.HOURS)
                .addTag(CALL_INFO_WORKER)
                .build();
    workManager.enqueue(callDataRequest);
}

But the value is always null, even if I put a breakpoint inside the Worker's doWork() method (so it is definitely in progress) and check the work status from another thread.


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/50357066/periodic-daily-work-requests-using-workmanager

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