Create a Repeating Task Using Coroutine

Hitesh Sahu
Mar 10, 2021

--

Example of how to create repeating Task using Kotlin Coroutine

add Coroutine in Build.gradle

implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2’

To create a repeating Job

/**
* start Job
* val job = startRepeatingJob()
* cancels the job and waits for its completion
* job.cancelAndJoin()
* Params
* timeInterval: time milliSeconds between next Tick
*/
private fun startRepeatingJob(timeInterval: Long): Job {
return CoroutineScope(Dispatchers.Default).launch {
while (NonCancellable.isActive) {

//repeate Task Here
delay(timeInterval)
}
}
}

To start Job:

Job repeatJob = startRepeatingJob(1000L)

To Stop Job:

secondTickJob.cancel()

Same approach using Handlers

repeateTaskkHandler = Handler()
taskRunnable= Runnable {
//repeate Task Here
repeateTaskkHandler?.postAtTime(taskRunnable, interval)
}
taskRunnable.run()

Stop:

if (secondClockHandler != null) {
repeateTaskkHandler?.removeCallbacks(taskRunnable)
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Responses (1)

Write a response