Tickers in Scala
Timers are for when you want to do something once in the future - tickers are for when you want to do something repeatedly at regular intervals. Here’s an example of a ticker that ticks periodically until we stop it.
In this Scala example, we’re using Akka’s scheduler to create a ticker. Akka is a popular toolkit for building concurrent and distributed applications in Scala.
We create an ActorSystem
and use its scheduler to schedule a task that repeats every 500 milliseconds. This is analogous to the ticker in the original example.
We then schedule another task to run after 1600 milliseconds, which cancels the ticker and terminates the actor system.
When we run this program, the ticker should tick 3 times before we stop it:
Note that the exact times will depend on when you run the program.
In Scala, we don’t have the exact equivalent of Go’s channels and select statement, so we’ve used Akka’s scheduling capabilities to achieve similar functionality. This approach is idiomatic in Scala when working with recurring tasks and timeouts.