HelloCW
HelloCW

Reputation: 2255

How can I set jobFinished() if I need to execute a repeated task with jobInfo?

I hope to execute a repeated task with JobScheduler.

I can't understand completely about the fun jobFinished() from official document.

Which code is correct between jobFinished(parameters, false) and jobFinished(parameters, true) if I hope the task can be executed repeatedly?

BTW, I have set setPeriodic(interval) for JobScheduler

Code

private fun startScheduleRestore(mContext:Context){
   logError("Start Server")

   val interval=10 *1000L

    val mJobScheduler = mContext.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler

    val jobInfo = JobInfo.Builder(mContext.getInteger(R.integer.JobID), ComponentName(mContext, RestoreService::class.java))
                        .setPeriodic(interval)
                        .setPersisted(true)
                        .build()

    mJobScheduler.schedule(jobInfo)
}



class RestoreService : JobService() {
    override fun onCreate() {
        logError("OnCreate")
        super.onCreate()
    }

    override fun onDestroy() {
        logError("OnDestory")
        super.onDestroy()
    }

    override fun onStartJob(params: JobParameters): Boolean {
        Thread(Runnable { completeRestore(params) }).start()
        return true
    }

    override fun onStopJob(params: JobParameters): Boolean {
        logError("OnStop")
        return false
    }


    fun completeRestore(parameters: JobParameters) {
        logError("Starting")
        jobFinished(parameters, false)
    }

}

Upvotes: 3

Views: 915

Answers (1)

Sagar
Sagar

Reputation: 24907

Based on the documentation:

You can request that the job be scheduled again by passing true as the wantsReschedule parameter. This will apply back-off policy for the job; this policy can be adjusted through the setBackoffCriteria(long, int) method when the job is originally scheduled. The job's initial requirements are preserved when jobs are rescheduled, regardless of backed-off policy.

jobFinished(parameters, true) will re-schedule your job.

If you want to execute something periodically, then use setPeriodic in your JobInfo.Builder

Upvotes: 1

Related Questions