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

stu*_*t93 6 android android-service periodic-task android-background firebase-job-dispatcher

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

            .setRecurring(true)
            // start between 0 and 60 seconds from now
            .setTrigger(Trigger.executionWindow(0, 60))
Run Code Online (Sandbox Code Playgroud)

我知道这.setRecurring使得这项工作是周期性的,并trigger使它以60秒的间隔开始,但第二次执行该怎么办?这是否意味着第二次从第一次开始也会执行60秒?

这不可能是真的,因为即使考虑到后台活动的优化以及服务运行的时间比他们预期的要晚一些,编程60秒,而工作大约在5/10/20分钟后运行太多了差异.官方文件说,差异是几秒钟,也许几分钟不超过20分钟.

基本上,我的问题是,这 .setTrigger(Trigger.executionWindow(0, 60))真的意味着这段时间是60秒还是我开始犯这个错误?

jee*_*pal 6

当它是非周期性的.

.setRecurring(false)
.setTrigger(Trigger.executionWindow(x, y))  
Run Code Online (Sandbox Code Playgroud)

此代码将在计划作业的x秒和计划作业的y秒之间运行我们的工作.

x被称为windowStart,这是作业应被视为有资格运行的最早时间(以秒为单位).从作业安排的时间开始计算(用于新工作)

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

当它是周期性的

.setRecurring(true)            
.setTrigger(Trigger.executionWindow(x, y))
Run Code Online (Sandbox Code Playgroud)

此代码将在计划作业的x秒和计划作业的y秒之间运行我们的工作.由于这是定期的,因此下一次执行将在作业完成后x秒安排.

也可以参考这个答案.


Dik*_*ika 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);
    }
Run Code Online (Sandbox Code Playgroud)

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