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

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

本文介绍了在 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 中将初始延迟设置为定期工作管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 10:14