Timers in Kotlin
import kotlinx.coroutines.*
import kotlin.time.Duration.Companion.seconds
suspend fun main() {
// Timers represent a single event in the future. You
// tell the timer how long you want to wait, and it
// provides a coroutine that will be executed at that
// time. This timer will wait 2 seconds.
val timer1 = GlobalScope.launch {
delay(2.seconds)
println("Timer 1 fired")
}
// The `timer1.join()` suspends the current coroutine until timer1 completes
timer1.join()
// If you just wanted to wait, you could have used
// `delay()`. One reason a timer may be useful is
// that you can cancel the coroutine before it fires.
// Here's an example of that.
val timer2 = GlobalScope.launch {
delay(1.seconds)
println("Timer 2 fired")
}
val job2 = timer2.job
val stop2 = job2.cancel()
if (stop2) {
println("Timer 2 stopped")
}
// Give the `timer2` enough time to fire, if it ever
// was going to, to show it is in fact stopped.
delay(2.seconds)
}
In Kotlin, we use coroutines to achieve similar functionality to Go’s timers. Here’s how the code works:
We import the necessary coroutine libraries and the
seconds
extension function for creating durations.The
main
function is marked assuspend
to allow the use of coroutine-specific functions likedelay
.Instead of
time.NewTimer
, we useGlobalScope.launch
to create a coroutine that will execute after a specified delay.We use
delay(2.seconds)
to wait for 2 seconds before executing the coroutine’s body.The
timer1.join()
call suspends the main coroutine untiltimer1
completes, similar to<-timer1.C
in Go.For the second timer, we again use
GlobalScope.launch
, but this time we keep a reference to theJob
object.To stop the timer, we call
job2.cancel()
instead oftimer2.Stop()
.Finally, we use
delay(2.seconds)
to wait and ensure the second timer doesn’t fire.
To run this program:
$ kotlinc timers.kt -include-runtime -d timers.jar
$ java -jar timers.jar
Timer 1 fired
Timer 2 stopped
The first timer will fire ~2s after we start the program, but the second should be stopped before it has a chance to fire.
Kotlin’s coroutines provide a more flexible and powerful way to handle asynchronous operations compared to Go’s timers, but the basic concept remains similar.