Schedule Jobs using JobScheduler in Android

The JobScheduler API allows to schedule jobs based on various conditions, not on exact time. These conditions can be whether the device is charging, idle, connected to a network or device’s battery level must not be low.

The job is created as a JobService subclass. We need to implement the onStartJob() and onStopJob() methods.

onStartJob()Called when the system decides that job should be executed.

Method returns boolean value. Return true if job needs to continue running on a separate thread. In this case we need to call jobFinished() method to tell that the job was completed. Return false if job was completed by the end of onStartJob().

The long-running jobs should be executed on a separate thread because the onStartJob() method is performed on the main thread.
onStopJob()Called when the system decides that job should be stopped before was completed. It can happen if conditions are no longer met. For example, device was disconnected from the network.

Method returns boolean value. Return true if need to reschedule the job. Return false if job should be ended.



import android.util.Log

class MyJobService : JobService()
    override fun onStartJob(params: JobParameters): Boolean
        Log.d("MY_APP", "Job started")

        Thread {
            for (i in 0..5) {
                Log.d("MY_APP", "$i")

            jobFinished(params, false)

        return true

    override fun onStopJob(params: JobParameters): Boolean
        return true

In the manifest file we need to register a newly created JobService with the BIND_JOB_SERVICE permission.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""

        <!-- ... -->
        <activity android:name=".MainActivity">
            <!-- ... -->
        <service android:name=".MyJobService"
            android:permission="android.permission.BIND_JOB_SERVICE" />


A JobInfo object contains the scheduling conditions which is used to determine when the job should be executed. A JobInfo can be constructed using the JobInfo.Builder. It accepts the job ID that can be used to cancel the job or to monitor if job is still running. The JobScheduler object contains the schedule() method which is used to schedule the job.



import android.content.ComponentName
import android.content.Context
import android.os.Bundle

class MainActivity : AppCompatActivity()
    override fun onCreate(savedInstanceState: Bundle?)

        val jobId = 1

        val jobService = ComponentName(this,
        val jobInfo = JobInfo.Builder(jobId, jobService)
            .setMinimumLatency(1)   // Wait at least 1 ms
            .setOverrideDeadline(5) // Maximum delay 5 ms

        val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler

Leave a Comment

Your email address will not be published. Required fields are marked *