Timers in Kotlin
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:
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.