-1

I want to run my job using Job Scheduler daily. I already looked at setPeriodic(long intervalMillis) but don't know how to use it to run the job daily in evening around 7:00PM (although not exact 7:00)

  public  void scheduleJob(View view){
    ComponentName serviceName = new ComponentName(getPackageName(),MJobService.class.getName());
    JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, serviceName);
    builder.setPersisted(true);

    JobInfo myJobInfo = builder.build();
    mScheduler.schedule(myJobInfo);


}
ulti72
  • 79
  • 1
  • 9

1 Answers1

1

JobScheduler is specifically designed for inexact timing. Your best option will be AlarmManager. Try like below:

private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
...
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 19);

alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
        1000 * 60 * 60 * 24, alarmIntent);

Implement your logic inside AlarmReceiver.

Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46
  • I dont need exact timing, but it should be around 7:00 PM, I used this because I read that on reboot Alarmmanger will not work. – ulti72 Nov 17 '19 at 11:56
  • There is nothing about **around**. Either at exact time or anytime within 24 hours. To solve boot problem you can use ` ` in `AndroidManifest` with BroadcastReceiver – Md. Asaduzzaman Nov 17 '19 at 12:02
  • thank you! One more thing, can we use WorkManager instead of AlarmManager here. – ulti72 Nov 17 '19 at 15:18
  • No, actually `WorkManager` internally use `JobScheduler`. For exact time scheduling AlarmManager is recommended. Hope this help you. Please accept the answer and hit upvote as usual. Thanks – Md. Asaduzzaman Nov 17 '19 at 15:59
  • @user6299305, if it will help you then accept the answer and hit upvote so that others can find it helpful. Thanks – Md. Asaduzzaman Nov 19 '19 at 06:45
  • Done, I need one more help. In some phones like one plus I think due to battery optimisation alarm manager not working. Will using setExactAndAllowWhileIdle() solve this problem, or I need whitelist or take permission for the app to bypass battery optimisation – ulti72 Nov 19 '19 at 14:52
  • @user6299305, Any problem? Why you reverse? – Md. Asaduzzaman Nov 20 '19 at 11:34