如何在不使用WorkManager立即运行的情况下更改定期工作请求期限? [英] How to change periodic work request period without it running immediately using WorkManager?

查看:130
本文介绍了如何在不使用WorkManager立即运行的情况下更改定期工作请求期限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

val request = PeriodicWorkRequestBuilder<FooWorker>(1, TimeUnit.DAYS).build()
WorkManager.getInstance().enqueueUniquePeriodicWork(
    "FOO",
    ExistingPeriodicWorkPolicy.REPLACE,
    request
)

上面的代码在ApplicationonCreate中运行,以确保请求被排队.但是,这会导致问题,因为ExistingPeriodicWorkPolicy.REPLACE取消先前的工作并排队新的工作,导致FooWorker会在用户每次启动应用程序时运行.

The code above is ran in onCreate of Application to ensure the request is enqueued. However, this will cause a problem where the FooWorker will run every time user start the application because ExistingPeriodicWorkPolicy.REPLACE cancel previous work and enqueue new work which cause it run immediately.

如果更改为ExistingPeriodicWorkPolicy.KEEP,即使更换了工期或更改了工作人员,我们也将无法替换工作.

If we change to ExistingPeriodicWorkPolicy.KEEP, we will not able to replace the work even the period or the worker is changed.

在当前请求运行之后,是否可以替换请求?

Is there a way to replace the request after the current one is running?

例如,原始请求每天运行1次,而新请求每小时运行1次.在运行下一个原始请求之后,将其替换为新请求.

For example, origin request run a 1 time per day and the new request is 1 time per hour. After the next origin request is ran, then replace it with new request.

推荐答案

无法通过干净的方式准确地完成定期工作.

There is no way to do exactly what you want with periodic work in a clean way.

但是,绝对不需要自己进行定期工作.通过在doWork方法的末尾安排下一个WorkRequest,就可以轻松地实现相同的结构,就在返回Result.SUCCESS之前:

However, there's absolutely no need to use periodic work itself. The same structure can be easily accomplished by scheduling the next WorkRequest at the end of your doWork method, right before returning Result.SUCCESS:

fun doWork(): Result {
  reallyDoWork()
  // Now schedule the next "periodic" work
  val request = OneTimeWorkRequestBuilder<FooWorker>().build()
  WorkManager.getInstance().enqueueUniqueWork(
    "FOO",
    ExistingWorkPolicy.REPLACE,
    request
  )
  return Result.SUCCESS
}

使用此设置,如果您已经有一个WorkRequest排队,并且您在ApplicationonCreate()排队时,可以安全地使用ExistingWorkPolicy.KEEP来避免重新安排工作,当下一个WorkRequest被触发时,下一个WorkRequest将与适当的新时期.

With this setup, your onCreate() of Application can safely use ExistingWorkPolicy.KEEP to avoid rescheduling work if you already have a WorkRequest queued up and when that queued up work fires, the next WorkRequest will be queued up with the appropriate new period.

这篇关于如何在不使用WorkManager立即运行的情况下更改定期工作请求期限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆