问题描述
因此,经过约束类之后,我没有找到任何功能在工作上增加时间限制.例如,我想在8:00 AM开始执行一项工作(该工作可以是 OneTimeWorkRequest 或 PeriodicWorkRequest ).如何添加约束以使用WorkManager安排这项工作.
Hence, After going though the Constraints class I haven't found any function to add time constraint on the work. For like example, I want to start a work to perform at 8:00am (The work can be any of two types OneTimeWorkRequest or PeriodicWorkRequest) in the morning. How can I add constraint to schedule this work with WorkManager.
推荐答案
很遗憾,您目前无法在特定时间安排工作.如果您有时间紧迫的实现,则应使用 setAndAllowWhileIdle()或 setExactAndAllowWhileIdle().
Unfortunately, you cannot schedule a work at specific time as of now. If you have time critical implementation then you should use AlarmManager to set alarm that can fire while in Doze to by using setAndAllowWhileIdle() or setExactAndAllowWhileIdle().
您可以使用WorkManager
安排一次具有一次初始延迟的工作或定期执行该工作,
You can schedule a work, with onetime initial delay or execute it periodically, using the WorkManager
as follows:
创建Worker类:
public class MyWorker extends Worker {
@Override
public Worker.WorkerResult doWork() {
// Do the work here
// Indicate success or failure with your return value:
return WorkerResult.SUCCESS;
// (Returning RETRY tells WorkManager to try this task again
// later; FAILURE says not to try again.)
}
}
然后按照以下时间表安排OneTimeWorkRequest
:
Then schedule OneTimeWorkRequest
as follows:
OneTimeWorkRequest mywork=
new OneTimeWorkRequest.Builder(MyWorker.class)
.setInitialDelay(<duration>, <TimeUnit>)// Use this when you want to add initial delay or schedule initial work to `OneTimeWorkRequest` e.g. setInitialDelay(2, TimeUnit.HOURS)
.build();
WorkManager.getInstance().enqueue(mywork);
您可以按以下步骤设置其他约束:
// Create a Constraints that defines when the task should run
Constraints myConstraints = new Constraints.Builder()
.setRequiresDeviceIdle(true)
.setRequiresCharging(true)
// Many other constraints are available, see the
// Constraints.Builder reference
.build();
然后创建一个使用这些约束的OneTimeWorkRequest
OneTimeWorkRequest mywork=
new OneTimeWorkRequest.Builder(MyWorker.class)
.setConstraints(myConstraints)
.build();
WorkManager.getInstance().enqueue(mywork);
PeriodicWorkRequest可以如下创建:
PeriodicWorkRequest periodicWork = new PeriodicWorkRequest.Builder(MyWorker.class, 12, TimeUnit.HOURS)
.build();
WorkManager.getInstance().enqueue(periodicWork);
这将创建一个PeriodicWorkRequest,以每12小时定期运行一次.
This creates a PeriodicWorkRequest to run periodically once every 12 hours.
这篇关于使用WorkManager安排在特定时间的工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!