【问题标题】:How to set the period of a periodic task in Firebase JobDispatcher?如何在 Firebase JobDispatcher 中设置周期性任务的周期?
【发布时间】:2017-07-25 13:50:21
【问题描述】:

我已经阅读了所有可用的官方文档(令人惊讶的是不是很多),对于定期任务,我所能得到的只是这段代码

            .setRecurring(true)
            // start between 0 and 60 seconds from now
            .setTrigger(Trigger.executionWindow(0, 60))

我知道.setRecurring 使作业周期性,trigger 使其以 60 秒的间隔开始,但是第二次执行呢?这是否意味着第二次也会从第一次开始执行 60 秒?

这不可能是真的,因为即使考虑到后台活动的优化以及服务的运行方式比预期的稍晚,编程 60 秒的周期,而作业运行大约 5/10/20 分钟后差别太大了。官方文档说相差几秒,可能几分钟不超过20分钟。

基本上,我的问题是.setTrigger(Trigger.executionWindow(0, 60)) 真的意味着周期是 60 秒还是我弄错了?

【问题讨论】:

    标签: android android-service android-background periodic-task firebase-job-dispatcher


    【解决方案1】:

    当它是非周期性时。

    .setRecurring(false)
    .setTrigger(Trigger.executionWindow(x, y))  
    

    此代码将在调度作业 x 秒和调度作业 y 秒之间运行我们的作业。

    x 被称为 windowStart,它是作业应该被认为有资格运行的最早时间(以秒为单位)。从安排作业的时间开始计算(针对新作业)

    y 被称为 windowEnd,作业应在理想世界中运行的最晚时间(以秒为单位)。计算方式与 windowStart 相同。

    周期性的时候

    .setRecurring(true)            
    .setTrigger(Trigger.executionWindow(x, y))
    

    此代码将在调度作业 x 秒和调度作业 y 秒之间运行我们的作业。由于这是周期性的,因此下一次执行将安排在作业完成后 x 秒。

    也可以参考this回答。

    【讨论】:

      【解决方案2】:

      看一下Trigger类here的源码就清楚了

      它说:

          /**
           * Creates a new ExecutionWindow based on the provided time interval.
           *
           * @param windowStart The earliest time (in seconds) the job should be
           *                    considered eligible to run. Calculated from when the
           *                    job was scheduled (for new jobs) or last run (for
           *                    recurring jobs).
           * @param windowEnd   The latest time (in seconds) the job should be run in
           *                    an ideal world. Calculated in the same way as
           *                    {@code windowStart}.
           * @throws IllegalArgumentException if the provided parameters are too
           *                                  restrictive.
           */
          public static JobTrigger.ExecutionWindowTrigger executionWindow(int windowStart, int windowEnd) {
              if (windowStart < 0) {
                  throw new IllegalArgumentException("Window start can't be less than 0");
              } else if (windowEnd < windowStart) {
                  throw new IllegalArgumentException("Window end can't be less than window start");
              }
      
              return new JobTrigger.ExecutionWindowTrigger(windowStart, windowEnd);
          }

      或者只需 Ctrl+单击Trigger,Android Studio 就会将您带到它的源代码。所以如果你写:.setTrigger(Trigger.executionWindow(0, 60)) 那么它将每秒运行一次

      【讨论】:

        猜你喜欢
        • 2017-07-18
        • 1970-01-01
        • 1970-01-01
        • 2019-05-25
        • 2018-11-28
        • 1970-01-01
        • 1970-01-01
        • 2011-10-06
        • 1970-01-01
        相关资源
        最近更新 更多