Timers in Nim
We often want to execute code at some point in the future, or repeatedly at some interval. Nim’s asyncdispatch
module provides features that make both of these tasks easy. We’ll look at timers in this example.
In this Nim program:
We import the
times
andasyncdispatch
modules, which provide the necessary timing and asynchronous functions.We define an asynchronous
main
procedure using the{.async.}
pragma.We create a timer using
sleepAsync(2000)
, which will wait for 2 seconds (2000 milliseconds).We use
await timer1
to block until the timer fires.We demonstrate cancelling a timer by creating a second timer and then immediately cancelling it.
We use
asyncCheck
to start an asynchronous operation without waiting for it to complete.Finally, we use
waitFor main()
to run the asynchronous main procedure.
To run the program, save it as timers.nim
and use the Nim compiler:
The first timer will fire ~2 seconds after we start the program, but the second should be stopped before it has a chance to fire.
This example demonstrates basic timer usage in Nim, including creating, waiting for, and cancelling timers in an asynchronous context.