代码之家  ›  专栏  ›  技术社区  ›  PPD

作业调度程序每15分钟执行一次

  •  2
  • PPD  · 技术社区  · 7 年前

    我正在应用程序中使用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 回复  |  直到 7 年前
        1
  •  1
  •   HedeH    7 年前

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

    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)

    指定此作业应按提供的间隔和弹性重新执行。作业可以在周期结束时在具有flex长度的窗口中随时执行。

    Illustration


    正如一些评论中已经推荐的,您应该开始使用新的 WorkManager (即使还没有达到生产水平)具有与 JobScheduler ,但它的最低SDK支持是14,这将允许您删除大量样板代码:)

        2
  •  0
  •   user3606010    7 年前

    从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);
        }