We often want to execute code at some point in the future, or repeatedly at some interval. Crystal’s standard library provides features that make both of these tasks easy. We’ll look first at timers.
The first timer will fire ~2s after we start the program, but the second should be stopped before it has a chance to fire.
In this Crystal version:
We use the Timer class from the standard library instead of Go’s time.Timer.
Instead of channels, we pass a block to the Timer constructor which will be executed when the timer fires.
We use Timer#wait to block until the timer fires, similar to <-timer.C in Go.
We use spawn to create a new fiber (Crystal’s lightweight thread) instead of a goroutine.
We use Timer#cancel to stop a timer, which is similar to Go’s timer.Stop().
The overall structure and functionality remain the same, demonstrating how to create, use, and cancel timers in Crystal.