Android JobScheduler run only once a day

Happo picture Happo · Aug 17, 2017 · Viewed 9k times · Source

I checkout the JobScheduler API which can be used since Android API level 21. I want to schedule a task which requires internet and runs only once a day or optional once a week (in case of successful execution). I found no examples about this condition. Can someone help me? Thanks.

Answer

Victor Rattis picture Victor Rattis · Aug 18, 2017

Follow a simple example for your question, I believe it will help you:

AndroidManifest.xml:

<service android:name=".YourJobService"
    android:permission="android.permission.BIND_JOB_SERVICE" />

YourJobService.java:

class YourJobService extends JobService {
    private static final int JOB_ID = 1;
    private static final long ONE_DAY_INTERVAL = 24 * 60 * 60 * 1000L; // 1 Day
    private static final long ONE_WEEK_INTERVAL = 7 * 24 * 60 * 60 * 1000L; // 1 Week

    public static void schedule(Context context, long intervalMillis) {
        JobScheduler jobScheduler = (JobScheduler) 
            context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
        ComponentName componentName =
            new ComponentName(context, YourJobService.class);
        JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, componentName);
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
        builder.setPeriodic(intervalMillis);
        jobScheduler.schedule(builder.build());
    }

    public static void cancel(Context context) {
        JobScheduler jobScheduler = (JobScheduler)
            context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
        jobScheduler.cancel(JOB_ID);    
    }

    @Override
    public boolean onStartJob(final JobParameters params) {
        /* executing a task synchronously */
        if (/* condition for finishing it */) {
            // To finish a periodic JobService, 
            // you must cancel it, so it will not be scheduled more.
            YourJobService.cancel(this);
        }

        // false when it is synchronous.
        return false;
    }

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

After scheduling the job, calling YourJobService.schedule(context, ONE_DAY_INTERVAL). It will only be called when connecting to some network and once inside the internal one day... ie once a day with connection to the network.

Obs.: The Periodic job can only be finished calling JobScheduler.cancel(Job_Id), jobFinished() method will not finish it.

Obs.: If you want to change it to "once a week" - YourJobService.schedule(context, ONE_WEEK_INTERVAL).

obs.: Periodic job on Android L can be run once at any time in the range you've set up.