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:

  1. We import the necessary coroutine libraries and the seconds extension function for creating durations.

  2. The main function is marked as suspend to allow the use of coroutine-specific functions like delay.

  3. Instead of time.NewTimer, we use GlobalScope.launch to create a coroutine that will execute after a specified delay.

  4. We use delay(2.seconds) to wait for 2 seconds before executing the coroutine’s body.

  5. The timer1.join() call suspends the main coroutine until timer1 completes, similar to <-timer1.C in Go.

  6. For the second timer, we again use GlobalScope.launch, but this time we keep a reference to the Job object.

  7. To stop the timer, we call job2.cancel() instead of timer2.Stop().

  8. 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.