Search code examples
androidandroid-jobscheduler

Scheduling a daily job at a particular time


I want to give an alert at 9 PM daily and I am planning to use Periodic job scheduler instead of Alarm Manager as to overcome doze mode issues.

How can this be done with job scheduler, as I want alert daily at 9PM?

Following is my code, is this right way of scheduling periodic tasks?

static JobScheduler jobScheduler;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static void scheduleJob(Context context) {
    Log.d("JobSchedularTest","scheduleJob.........");

    ComponentName componentName = new ComponentName(context, MyJobService.class);
    JobInfo.Builder builder = new JobInfo.Builder(100, componentName);
    // diff_nine_pm_time_in_milli = difference between current time and 9PM time
    builder.setMinimumLatency(diff_nine_pm_time_in_milli);
    builder.setOverrideDeadline(diff_nine_pm_time_in_milli);
    jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    jobScheduler.schedule(builder.build());
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static void stopJob(){
    if(jobScheduler!=null)
        jobScheduler.cancel(100);
}

Solution

  • If you need to deliver an alert exactly at 9 PM, AlarmManager might still be the best option for you. A job scheduled with JobScheduler, if the device is in doze mode, will only be executed during a maintenance window.

    As stated here:

    The AlarmManager API is another option that the framework provides for scheduling tasks. This API is useful in cases in which an app needs to post a notification or set off an alarm at a very specific time.

    Even though AlarmManager's setExact method is strongly discouraged, if your app does depend on an exact-time alert, that's your best alternative.

    On the other hand, if your alert can be delayed depending on maintenance windows and priority buckets, it's better to use jobs, and your code seems to do the trick.