Scheduling a periodic JobService only if it is not scheduled already

225 Views Asked by At

I'm trying to schedule a periodic job service like below.

The problem here is that jobScheduler.getPendingJob(jobId) always returns null after the job is executed once, i.e., jobScheduler.allPendingJobs does not have my job after it is executed the first time.

I do not want to schedule it again because I end up running the job twice within the same period.

If I don't reschedule it, then the job runs perfectly fine, every hour.

fun scheduleAnalyticsJob() {
    logPendingJobs()

    val jobId = analyticsJobsId
    LogUtil.debug(this, "Analytics job id [$jobId].")

    val job = JobInfo.Builder(
        jobId,
        ComponentName(appContext, ScheduledAnalyticsJob::class.java)
    )
        .setRequiresCharging(false)
        .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
        .setPeriodic(IntervalMillis.hour)
        .setPersisted(true)
        .build()

    val pendingJob = jobScheduler.getPendingJob(jobId)
    if (pendingJob == null) {
        LogUtil.debug(this, "Rescheduling analytics job.")
        jobScheduler.schedule(job)
    } else if (pendingJob != job) {
        LogUtil.debug(this, "Rescheduling analytics job since params changed.")
        jobScheduler.cancel(jobId)
        jobScheduler.schedule(job)
    } else {
        LogUtil.debug(this, "Analytics Job already scheduled.")
    }
}
0

There are 0 best solutions below