JobScheduler 每 15 分钟执行一次

JobScheduler executes after every 15 min

我在我的应用程序中使用了 JobScheduler。如果用户连接到 WIFI,我想在每小时后上传文件,但是 onStartJob() 方法在一小时前被调用,大部分是在 15-20 分钟后被调用。以下是我的代码:

ComponentName componentName = new ComponentName(this,UploadService.class);
    JobInfo info = new JobInfo.Builder(1,componentName)
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED) // change this later to wifi
            .setPersisted(true)
            .setPeriodic(60*60*10000)
            .build();

    JobScheduler scheduler = (JobScheduler)getSystemService(JOB_SCHEDULER_SERVICE);
    int resultCode = scheduler.schedule(info);
    if (resultCode==JobScheduler.RESULT_SUCCESS) {
        Log.d(TAG,"JOb Scheduled");
    } else {
        Log.d(TAG,"Job Scheduling fail");
    }

public class UploadService extends JobService {
@Override
public boolean onStartJob(JobParameters params) {
    uploadFileToServer(params);
    return true;
}

@Override
public boolean onStopJob(JobParameters params) {
    return true;
}
.....
.....
}

这里 uploadFileToServer(params); 在小时之前被调用。如何设置时间,使其仅在一小时后调用。提前致谢

来自 JobInfo.java class , 您无法控制在此间隔内何时执行此作业

    /**
     * Specify that this job should recur with the provided interval, not more than once per
     * period. You have no control over when within this interval this job will be executed,
     * only the guarantee that it will be executed at most once within this interval.
     * Setting this function on the builder with {@link #setMinimumLatency(long)} or
     * {@link #setOverrideDeadline(long)} will result in an error.
     * @param intervalMillis Millisecond interval for which this job will repeat.
     */
    public Builder setPeriodic(long intervalMillis) {
        return setPeriodic(intervalMillis, intervalMillis);
    }

JobInfo.Builder 上使用此方法 setPeriodic (long intervalMillis, long flexMillis)在 API 24 中添加)并提供弹性间隔作为第二个参数:

long flexMillis = 59 * 60 * 1000; // wait 59 minutes before executing next job    

JobInfo info = new JobInfo.Builder(1,componentName)
        .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED) // change this later to wifi
        .setPersisted(true)
        .setPeriodic(60 * 60 * 1000, flexMillis)
        .build();

重要 - 工作在弹性间隔(在最后一个工作完成后开始)后保证 运行,但不保证 [=34] =] 紧随其后,因此作业之间的持续时间可能超过 1 小时,具体取决于您的作业要求、系统状态等...

文档参考:https://developer.android.com/reference/android/app/job/JobInfo.Builder.html#setPeriodic(long,%20long)

Specify that this job should recur with the provided interval and flex. The job can execute at any time in a window of flex length at the end of the period.


正如一些评论中已经推荐的那样,您应该开始使用新的 WorkManager(即使它还不是生产级别),它具有与 JobScheduler 相似的功能,但它是最低 SDK 支持是 14,这会让你删除很多样板代码 :)