I'm implementing an SDK and I want to schedule a job that logs a message every 15 min(in the background). It works properly for the first 15 min but after that, it logs about every minute. this is my code below
class UploadJobService : JobService() {
companion object {
private const val TAG = "TAG"
}
override fun onStartJob(params: JobParameters): Boolean {
Log.d(TAG, "Job started")
doBackgroundWork()
return true
}
override fun onStopJob(params: JobParameters): Boolean {
Log.d(TAG, "Job cancelled before completion")
return true
}
private fun doBackgroundWork(params: JobParameters?){
job = CoroutineScope(Dispatchers.IO).launch {
delay(2000)
Log.d(TAG, "doBackgroundWork: Upload your file")
jobFinished(params, true)
}
}
}
and also
class UploadFilePeriodic {
companion object {
val TAG = "TAG"
private const val JOB_ID = 123
fun scheduleJob(context: Context) {
val info = JobInfo.Builder(JOB_ID, ComponentName(context, UploadJobService::class.java))
.setPeriodic(15 * 60 * 1000)
.setPersisted(true)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.build()
val scheduler = context.getSystemService(JOB_SCHEDULER_SERVICE) as JobScheduler
val resultCode = scheduler.schedule(info)
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d(TAG, "Job scheduled")
} else {
Log.d(TAG, "Job scheduling failed")
}
}
fun cancelJob(context: Context) {
val scheduler = context.getSystemService(JOB_SCHEDULER_SERVICE) as JobScheduler?
scheduler!!.cancel(JOB_ID)
Log.d(TAG, "Job cancelled")
}
}
}
Also, did I use the coroutine correctly? Could anyone help me to fix it please?