Tickers in Kotlin

Tickers are used when you want to do something repeatedly at regular intervals. Here’s an example of a ticker that ticks periodically until we stop it.

import kotlinx.coroutines.*
import kotlin.time.Duration.Companion.milliseconds

suspend fun main() = coroutineScope {
    // Tickers use a similar mechanism to timers: a
    // channel that is sent values. Here we'll use a
    // coroutine to emit values every 500ms.
    val ticker = ticker(500.milliseconds, 0)
    val job = launch {
        for (unit in ticker) {
            println("Tick at ${System.currentTimeMillis()}")
        }
    }

    // Tickers can be stopped. Once a ticker
    // is stopped it won't receive any more values.
    // We'll stop ours after 1600ms.
    delay(1600)
    ticker.cancel()
    job.cancel()
    println("Ticker stopped")
}

To run this program, you’ll need to add the kotlinx-coroutines-core dependency to your project. When we run this program, the ticker should tick 3 times before we stop it.

$ kotlinc -cp kotlinx-coroutines-core-1.5.2.jar tickers.kt -include-runtime -d tickers.jar
$ java -jar tickers.jar
Tick at 1634567890123
Tick at 1634567890623
Tick at 1634567891123
Ticker stopped

In this Kotlin version:

  1. We use Kotlin coroutines instead of goroutines.
  2. The ticker function from kotlinx.coroutines is used to create a ticker that emits Unit values at regular intervals.
  3. We launch a coroutine that collects values from the ticker and prints the current time for each tick.
  4. Instead of using a select statement, we use a for loop to receive values from the ticker.
  5. We use delay instead of time.Sleep to wait for 1600 milliseconds.
  6. To stop the ticker, we call cancel() on both the ticker and the job.

This example demonstrates how to use tickers in Kotlin with coroutines, which provides a similar functionality to Go’s tickers.