1

Is there a way to run a task once the same day and every consequent day at the specified time? I am using a library called "android-job" since it persists the scheduled jobs even after device reboot. I have been struggling to make this library work for my use case with no luck.

Note: the final goal is to start and stop a background service at the specified times every day. For example, I want to stop my service at 8pm and start it again at 8am).

Currently, my code looks like that:

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 20);
calendar.set(Calendar.MINUTE, 0);

int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);

long startMs = TimeUnit.MINUTES.toMillis(60 - minute) + TimeUnit.HOURS.toMillis((24 - hour) % 24);
long endMs = startMs + TimeUnit.MINUTES.toMillis(5);


int jobId = new JobRequest.Builder(TAG)
        .setExecutionWindow(startMs, endMs)
        .setPersisted(true)
        .setUpdateCurrent(updateCurrent)
        .build()
        .schedule();`

The console output:

jobInfo success, request{id=11, tag=job_demo_tag}, start 05:00:00, end 05:05:00, reschedule count 0
halfer
  • 19,824
  • 17
  • 99
  • 186
Georgi Koemdzhiev
  • 11,421
  • 18
  • 62
  • 126

1 Answers1

1

You can explore AlarmManager for this. It can be used for cases where you want to have your code execute at specified time even when your app isn't running.

https://developer.android.com/reference/android/app/AlarmManager.html

CoderP
  • 1,361
  • 1
  • 13
  • 19
  • Yes, I have explored the AlarmManager prior to trying the library. To my knowledge a scheduled alarm wont survive a device reboot. That is the reason I want to use the library – Georgi Koemdzhiev Mar 01 '17 at 11:01
  • 1
    I think that can be achieved by implementing a Boot Receiver. – CoderP Mar 01 '17 at 11:11
  • I see. So for example, if I schedule a task to call my receiver (and the receiver to do a task) at a specific time and If the device reboots, my receiver to receive the intent and schedule the task again? Is that what you are impaling? That might work. – Georgi Koemdzhiev Mar 01 '17 at 11:14
  • 1
    Yup. This should work. We have used this logic in a similar (not exact) use case. – CoderP Mar 01 '17 at 11:17
  • Thank you for your suggestion. I will test this logic to see if it will work for my usecase. I hope this logic to work as I have spend a log of hours trying to implement this usecase for my app :) – Georgi Koemdzhiev Mar 01 '17 at 11:25