Tickers in Nim
Our example demonstrates how to use tickers in Nim. Tickers are useful when you want to perform an action repeatedly at regular intervals.
import std/times
import std/asyncdispatch
proc main() {.async.} =
# Create a ticker that ticks every 500 milliseconds
var ticker = newTimer(500)
var done = newFuture[void]()
# Start an asynchronous procedure to handle the ticks
asyncCheck (proc() {.async.} =
while true:
try:
# Wait for either the ticker to tick or the done signal
let timeoutFuture = ticker.wait()
yield timeoutFuture or done
if done.finished:
break
echo "Tick at ", now()
except CancelledError:
break
)()
# Let the ticker run for 1600 milliseconds
await sleepAsync(1600)
# Stop the ticker and signal completion
ticker.clear()
done.complete()
echo "Ticker stopped"
waitFor main()
In this Nim version, we use the asyncdispatch
module to handle asynchronous operations, which is similar to Go’s concurrency model. We create a timer that ticks every 500 milliseconds using newTimer
.
We start an asynchronous procedure that waits for either the ticker to tick or a done signal. This is analogous to the select
statement in the original Go code.
The main procedure lets the ticker run for 1600 milliseconds using sleepAsync
, then stops the ticker by clearing it and signaling completion.
When we run this program, the ticker should tick 3 times before we stop it:
$ nim c -r tickers.nim
Tick at 2023-05-25T10:15:30+02:00
Tick at 2023-05-25T10:15:31+02:00
Tick at 2023-05-25T10:15:31+02:00
Ticker stopped
This example demonstrates how to use tickers in Nim for repeated actions at regular intervals, and how to stop them when they’re no longer needed.