shrub/pkg/hs-urbit/lib/Urbit/Behn.hs
Benjamin Summers c474a94d13 stylish-haskell
2019-07-12 12:27:15 -07:00

50 lines
1.2 KiB
Haskell

{-
# Behn
This provides a timer. To use this,
- Create a new timer with `init`.
- Use `doze` to start the timer.
- Call `wait` to wait until the timer fires.
Then, `wait` will return when the specified time has come.
- If the specified time was in the past, `wait` will return immediately.
- If a timer is set again, the old timer will not fire. The new time
replaces the old one.
- If a timer is unset (with `doze _ Nothing`), the timer will not fire
until a new time has been set.
-}
module Urbit.Behn (Behn(..), init, wait, doze) where
import Control.Lens
import Prelude hiding (init)
import Control.Concurrent.MVar (MVar, newEmptyMVar, putMVar, takeMVar)
import qualified Urbit.Time as Time
import qualified Urbit.Timer as Timer
-- Behn Stuff ------------------------------------------------------------------
data Behn = Behn
{ bTimer :: Timer.Timer
, bSignal :: MVar ()
}
init :: IO Behn
init = do
tim <- Timer.init
sig <- newEmptyMVar
pure (Behn tim sig)
wait :: Behn -> IO ()
wait (Behn _ sig) = takeMVar sig
doze :: Behn -> Maybe Time.Wen -> IO ()
doze behn Nothing = Timer.stop (bTimer behn)
doze (Behn tim sig) (Just t) =
Timer.start tim (t ^. Time.systemTime) (putMVar sig ())