上一回,我们已经简单地实现了一个单次任务,即通过OneTimeWorkRequest
构造的任务请求。今天,来试试一个周期性任务请求:PeriodicWorkRequest
周期性任务
为简单起见,延用之前的Worker任务就行了。
下面来构造周期性任务的request。同样地,使用kotlin扩展builder来构造:
1 |
|
可以看出,任务要求是: 每间隔1秒钟,执行一次任务
接着,执行此任务:
1 |
|
和单次任务是一模一样的。
执行结果
直接来看看执行结果:
1 |
|
任务发出后,马上就执行了一次,但是,我们想要的一秒后再次执行,并没有成功! 为什么呢?第二次、第三次执行都相隔了15分钟?!
分析
官方文档是时候出来了:
A WorkRequest for repeating work. This work executes multiple times until it is cancelled, with the first execution happening immediately or as soon as the given Constraints are met. The next execution will happen during the period interval; note that execution may be delayed because WorkManager is subject to OS battery optimizations, such as doze mode. You can control when the work executes in the period interval more exactly - see PeriodicWorkRequest.Builder for documentation on flexIntervals. Periodic work has a minimum interval of 15 minutes. Periodic work is intended for use cases where you want a fairly consistent delay between consecutive runs, and you are willing to accept inexactness due to battery optimizations and doze mode. Please note that if your periodic work has constraints, it will not execute until the constraints are met, even if the delay between periods has been met.
要点出炉:
- 第一次执行确实是立即的
- 执行可能被延迟,受系统耗电控制逻辑影响,以及doze模式等
- 周期任务最少是15分钟
所以,我们的1秒钟,将被系统忽略,最终使用了最少的15分钟。这其实和AlarmManager的规则是一样的,包括电池及doze的影响,都是延续AlarmManager。
带延时参数的周期任务
周期性任务还可以传入一个参数,以控制任务实际的执行时间。
1 |
|
其中,builder比普通的调用,增加了flexInterval参数,什么意思呢?来看看注释
1 |
|
首先,任务的执行时机,是每个周期的的flex时间区间,执行一次。其次,flex的区间排在整个周期的结尾。周期的最小值是15分钟,flex的最小值是5分钟。
也就是说,带flex参数的任务发出后,如果flex小于周期,那首次任务执行时间就有机会做到延时效果(上面的“before flex”就是这个实际的延时时间)。
构造一个周期为30分钟,flex为20分钟的请求并发出任务:
1 |
|
结果如下:
1 |
|
关注下时间就可知道事件序列:10:47发出任务 -> 10分钟(30 - 20)后,执行第一次任务 -> 30分钟(第一周期20分钟flex + 第二周期10分钟延时)后,执行第二次任务
。其实总的看来,就是第一个任务延时(interval - flex),之后每间隔interval执行一次。
小结
周期任务的介绍到此结束。但其实还有一个小问题 —— 带延时任务的输出结果实际是被干扰了的,实际如下:
1 |
|
中间夹杂着上一次创建的周期任务的执行日志 —— 原来上一个一般性周期任务还在执行!那么,我们自然应该想到:周期性任务如何取消呢?下回分解……