WorkManager系列(七)Recurring work

应用有时需周期性执行任务,如备份数据、下载内容或上传日志。可使用PeriodicWorkRequest执行此类任务,它不能链式执行。文中介绍了创建PeriodicWorkRequest的方法,其重复间隔最小为15分钟,执行时间受约束条件和系统优化影响,还可像观察一次性任务一样观察其状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Your application may at times require that certain tasks run periodically. For example, you may want to periodically backup your data, download fresh content in your app, or upload logs to a server.

Use the PeriodicWorkRequest for such tasks that need to execute periodically.

PeriodicWorkRequest cannot be chained. If your task requires chaining of tasks, consider OneTimeWorkRequest.

Here is how you can create a PeriodicWorkRequest:

Constraints constraints = new Constraints.Builder()
        .setRequiresCharging(true)
        .build();

PeriodicWorkRequest saveRequest =
        new PeriodicWorkRequest.Builder(SaveImageFileWorker.class, 1, TimeUnit.HOURS)
                  .setConstraints(constraints)
                  .build();

WorkManager.getInstance()
    .enqueue(saveRequest);

The example showcases a periodic work request with a one hour repeat interval.

The repeat interval is defined as the minimum time between repetitions. The exact time that the worker is going to be executed depends on the constraints that you are using in your work request and on the optimizations done by the system.

In the example, the PeriodicWorkRequest also requires the device to be plugged in. In this case, even if the defined repeat interval of an hour passes, the PeriodicWorkRequest will run only when the device is plugged in.

Note: The minimum repeat interval that can be defined is 15 minutes (same as the JobScheduler API).

You can observe the status of PeriodicWorkRequests the same way as OneTimeWorkRequests. Read more about observing work.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值