Control.Timeout

control-timeout-0.1.2: Timeout handling

Control.Timeout

Description

This module handles timeouts by using a (single) thread sitting in threadDelay and the STM. One can request an IO action be performed after some number of seconds and later cancel that request if need be.

The number of threads used is constant.

Synopsis

- addTimeout :: Float -> IO () -> IO TimeoutTag
- addTimeoutAtomic :: Float -> IO (IO () -> STM TimeoutTag)
- cancelTimeout :: TimeoutTag -> STM Bool
- data TimeoutTag

# Documentation

addTimeout

Arguments

:: Float | the number of seconds in the future to perform the action
-> IO () | the action to perform
-> IO TimeoutTag |

Add an action to be performed at some point in the future. The action will occur inside a thread which is dedicated to performing them so it should run quickly and certainly should not block on IO etc.

addTimeoutAtomic

Arguments

:: Float | the number of seconds in the future to perform the action
-> IO (IO () -> STM TimeoutTag) | an action to add the timeout and return the tag

Similar in function to addTimeout above, this call splits the IO and STM parts of the process so that a timeout can be added atomically. Consider the following code:

- We add a timeout with an action which reads from a global TVar
- We add the TimeoutTag (in case we wish to handle the timeout) and some bookkeeping data to the global TVar and trigger some external action (i.e. a network request)

In this case, the timeout could occur before the bookkeeping is added. Now the timeout code won't find the correct state. If we switch the two actions then we don't have the TimeoutTag to add to the bookkeeping structure and we would need another TVar, or some such, to fill in later.

cancelTimeout

Arguments

:: TimeoutTag | the tag returned by addTimeout
-> STM Bool | returns False if the timeout didn't exist

Remove a timeout. This function never fails, but will return False if the given timeout couldn't be found. This may be because cancelTimeout has already been called with this tag, or because the timeout has already fired. Note that, since timeouts are IO actions, they don't run atomically. Thus it's possible that this call returns False and that the timeout is currently in the process of running.

Note that one should never call cancelTimeout twice with the same tag since it's possible that the tag will be reused and thus the second call could cancel a different timeout.

data TimeoutTag

This is an opaque type of timeouts. A value of this type is returned when creating a timeout and can be used to cancel the same timeout.