androidandroid-servicescheduled-tasksandroid-jobschedulerandroid-job

Is there a way to run a task once the same day and every consequent day at the specified time?


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

Solution

  • 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