如何在Firebase JobDispatcher中设置周期性任务的周期?

6

我已经阅读了所有可用的官方文档(其实并不多),关于周期性任务,我只找到了这段代码。

            .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秒,还是我理解错了?
2个回答

6
当它是非周期性的时候。
.setRecurring(false)
.setTrigger(Trigger.executionWindow(x, y))  

这段代码将在作业安排时间后x秒和y秒之间运行我们的任务。 x被称为windowStart,它是任务应该被视为可运行的最早时间(以秒为单位)。对于新作业,从作业调度时计算。 y被称为windowEnd,在理想情况下,这是任务应该运行的最晚时间(以秒为单位)。以与windowStart相同的方式计算。
当它是周期性的时候。
.setRecurring(true)            
.setTrigger(Trigger.executionWindow(x, y))

这段代码将在任务被调度的x秒后和y秒之间运行我们的作业。由于这是定期执行,因此下一次执行将在作业完成x秒后被调度。

也可以参考这个答案。


0

如果您查看Trigger类的源代码此处,它会更清晰明了。

它声明:

    /**
     * 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)) 那么它将会每秒运行一次。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接