Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android JobScheduler running way too often when using setPeriodic()

I noticed my scheduled JobScheduler is executing the job way too often. I have it set to execute daily and it requires to be idle, to be on wlan and to be charging, but when those conditions are met the job executes like every 10min or even more frequently.

My code:

JobInfo.Builder builder = new JobInfo.Builder(1,
                    new ComponentName(context.getPackageName(), SyncJobService.class.getName()));


builder.setPeriodic(TimeUnit.DAYS.toMillis(1))
        .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
        .setRequiresCharging(true)
        .setRequiresDeviceIdle(true);

int code = jobScheduler.schedule(builder.build());
if (code <= 0) {
    Log.e(TAG, "Could not scheduled job: " + code);
    return;
}

Log.e(TAG, "Scheduled job");

The job executes a background thread to download data from the internet, and after the data download is done I call

mService.jobFinished(mParams, true);

to notify the job scheduler that the job is done and it should reschedule it. How come the job executes so often even when the period is set to one day? My android 6.0.1 device almost never enters doze mode because of the job running so often.

like image 729
qwertz Avatar asked Apr 29 '16 18:04

qwertz


1 Answers

after the data download is done I call mService.jobFinished(mParams, true); to notify the job scheduler that the job is done and it should reschedule it

That is your problem right there. Use false, not true.

false says, "the work is done for this job". true says "we had a problem, please reschedule this job again to happen soonish". For example, the criteria says that you have to have an Internet connection, but perhaps you are having difficulty connecting to your server. In that case, return true, in hopes that the problem will clear up in a bit.

You might also consider adjusting the backoff rules via setBackoffCriteria() for those cases where you really want to return true.

like image 130
CommonsWare Avatar answered Oct 21 '22 21:10

CommonsWare