[Haskell-cafe] Running an action periodically

Tristan Seligmann mithrandi at mithrandi.net
Fri Nov 24 20:53:54 UTC 2017


I just wrote this helper:

> import Control.Concurrent
> import Control.Concurrent.STM
> import Control.Exception.Safe
>
> pollT :: Int -> IO a -> IO (STM (Maybe a), Async b)
> pollT delay act = do
>   tv <- atomically (newTVar Nothing)
>   as <-
>     async . forever $ do
>       r <- tryAny act
>       case r of
>         Left _ -> pure ()
>         Right r' -> atomically (writeTVar tv (Just r'))
>       threadDelay delay
>   pure (readTVar tv, as)

I was sort of surprised not to find something like this in an existing
library.

   1. Did I miss an existing implementation?
   2. Any problems with this one?
   3. Any suggestions for a better name?
   4. Any thoughts on the general idea? That is, "run an action
   periodically, updating a TVar with the result".

There's a couple of obvious variations that can be built on top of this,
like retrying if the TVar is Nothing when reading from it, or writing
Nothing to the TVar when the action fails rather than keeping the old
value. Maybe passing in the old value to the action?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20171124/e6542776/attachment.html>


More information about the Haskell-Cafe mailing list