Search code examples
javaandroidkotlinjobsandroid-jobscheduler

How to specify a initial delay to an Android periodic job using JobScheduler?


I want to create a running job with a specific time and a given periodicity. For example, I want to schedule a job the second day of each month and it should run every month.

Looking at the JobInfo.Builder documentation I haven't found a way to set an initial delay.

Any idea on how could I achieve this?

Here is the code that runs with the correct periodicity but not with the initial delay I want:

fun build(application: Application, periodicity: Days, startDay: Days) {
    val serviceComponent = ComponentName(application, GenerateDebtJobService::class.java)
    val builder = JobInfo.Builder(1, serviceComponent)
        .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
        .setPeriodic(TimeUnit.DAYS.toMillis(periodicity.days.toLong()))

    (application.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler).schedule(builder.build())

Solution

  • You can't apply an initial delay for the periodic job. Currently should may use a one shot job for the initial delay and then schedule a new periodic job with the periodic interval.