在 Android 中将初始延迟设置为定期工作管理器

编程入门 行业动态 更新时间:2024-10-11 19:17:37
本文介绍了在 Android 中将初始延迟设置为定期工作管理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个 Worker 实例,需要每 24 小时运行一次,考虑到 PeriodicWorkRequest API,这非常简单.但这就是问题所在.

如果用户在晚上 8 点开始工作,我需要工作管理器的第一个实例在第二天早上 9 点运行,然后遵循 24 小时周期约束.

我看了这里发现 OneTimeWorkRequest API 有一个可以使用的 setInitialDelay() 函数,但我找不到 PeriodicWork API 的任何内容.

对此有一些技巧,例如我可以使用具有初始延迟的 OneTimeWork,然后从那里安排 PeriodicWork,但这有点脏.>

是否有任何方法可以仅使用 PeriodicWorkRequest API 来做到这一点?

解决方案

关于新版工作管理器 (2019 年 5 月 16 日发布的版本 2.1.0-alpha02)PeriodicWorkRequests 现在支持初始延迟.您可以使用 PeriodicWorkRequest.Builder 上的 setInitialDelay 方法来设置初始延迟.

示例:

PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(WorkerReminderPeriodic.class,24,时间单位.HOURS,PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS,时间单位.MILLISECONDS).setInitialDelay(1, TimeUnit.HOURS).addTag("send_reminder_periodic").建造();WorkManager.getInstance().enqueueUniquePeriodicWork("send_reminder_periodic", ExistingPeriodicWorkPolicy.REPLACE, workRequest);

I have a Worker instance that needs to run every 24 hours which is pretty simple considering the PeriodicWorkRequest API. But here's the catch.

If the user initiates the work at say 8 PM, I need the first instance of the work manager to run at 9 AM the next morning and then follow the 24-hour periodic constraint.

I looked hereand I found that the OneTimeWorkRequest API has a setInitialDelay() function that can be used but I wasn't able to find anything for the PeriodicWork API.

Ther are some hacks for this such as I can use the OneTimeWork with the initial delay and then schedule a PeriodicWork from there but it's kinda a dirty hack.

Is there any way to do this with just the PeriodicWorkRequest API?

解决方案

On the new version of Work manager (Version 2.1.0-alpha02 released on May 16, 2019) PeriodicWorkRequests now support initial delays. You can use the setInitialDelay method on PeriodicWorkRequest.Builder to set an initial delay.

Example:

PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder( WorkerReminderPeriodic.class, 24, TimeUnit.HOURS, PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS, TimeUnit.MILLISECONDS) .setInitialDelay(1, TimeUnit.HOURS) .addTag("send_reminder_periodic") .build(); WorkManager.getInstance() .enqueueUniquePeriodicWork("send_reminder_periodic", ExistingPeriodicWorkPolicy.REPLACE, workRequest);

更多推荐

在 Android 中将初始延迟设置为定期工作管理器

本文发布于:2023-10-18 15:13:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504601.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:管理器   设置为   中将   工作   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!