JobScheduler每15分钟执行一次

时间:2018-07-12 11:13:25

标签: android job-scheduling

我在应用程序中使用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);在小时前被呼叫。如何设置时间,以便仅在小时后才调用。预先感谢

2 个答案:

答案 0 :(得分:1)

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

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();

重要-可以确保作业在弹性间隔(最后一个作业完成后开始)之后运行,但不能保证在此间隔之后立即运行,因此作业之间的持续时间可以超过1小时,具体取决于您的工作要求,系统状态以及更多...

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

  

指定该作业应以提供的间隔和弹性重复进行。在该周期结束时,作业可以随时在弹性长度窗口中执行。

Illustration


正如一些评论中所建议的那样,您应该开始使用与JobScheduler类似的新WorkManager(即使它还不是生产级别),但是SDK的最低支持为14这将使您删除很多样板代码:)

答案 1 :(得分:0)

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

    /**
     * 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);
    }