Timeouts in Haskell
Timeouts are important for programs that connect to external resources or that otherwise need to bound execution time. Implementing timeouts in Haskell can be achieved using the timeout
function from the System.Timeout
module.
In this Haskell version:
We use
threadDelay
to simulate a slow operation. It takes microseconds as an argument, so we multiply seconds by 1,000,000.The
timeout
function fromSystem.Timeout
is used to implement the timeout mechanism. It takes a time in microseconds and an IO action, and returnsNothing
if the action doesn’t complete within the specified time, orJust result
if it does.We use pattern matching with
case
expressions to handle the results oftimeout
.Unlike in the original example, we don’t need to use channels or select statements, as Haskell’s
timeout
function provides a more straightforward way to implement timeouts.
Running this program shows the first operation timing out and the second succeeding:
This example demonstrates how to implement timeouts in Haskell, which is useful for bounding the execution time of operations that might take too long to complete.