Our first example demonstrates the use of timers in Haskell. We often want to execute code at some point in the future, or repeatedly at some interval. Haskell’s threadDelay function and the async library can help us achieve these tasks easily.
To run the program, save it as timers.hs and use runhaskell:
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 Haskell version:
We use threadDelay to create delays. The argument to threadDelay is in microseconds, so we multiply by 1,000,000 to get seconds.
Instead of channels, we use the async library to create asynchronous actions that can be cancelled.
The cancel function is used to stop the second timer before it fires.
We use putStrLn for output and hFlush stdout to ensure all output is displayed immediately.
This example demonstrates basic timer functionality in Haskell, including creating timed events and cancelling them before they occur.