on 2f706b9 help sign in
69 lines 2.3 kB history raw
1-- |
2-- Module : Streamly.Time
3-- Copyright : (c) 2017 Harendra Kumar
4--
5-- License : BSD3
6-- Maintainer : harendra.kumar@gmail.com
7-- Stability : experimental
8-- Portability : GHC
9--
10-- Time utilities for reactive programming.
12module Streamly.Time
13 ( periodic
14 , withClock
15 )
16where
18import Control.Monad (when)
19import Control.Concurrent (threadDelay)
21-- | Run an action forever periodically at the given frequency specified in per
22-- second (Hz).
23--
24-- @since 0.1.0
25periodic :: Int -> IO () -> IO ()
26periodic freq action = do
27 action
28 threadDelay (1000000 `div` freq)
29 periodic freq action
31-- | Run a computation on every clock tick, the clock runs at the specified
32-- frequency. It allows running a computation at high frequency efficiently by
33-- maintaining a local clock and adjusting it with the provided base clock at
34-- longer intervals. The first argument is a base clock returning some notion
35-- of time in microseconds. The second argument is the frequency in per second
36-- (Hz). The third argument is the action to run, the action is provided the
37-- local time as an argument.
38--
39-- @since 0.1.0
40withClock :: IO Int -> Int -> (Int -> IO ()) -> IO ()
41withClock clock freq action = do
42 t <- clock
43 go t period period t 0
45 where
47 period = 1000000 `div` freq
49 -- Note that localTime is roughly but not exactly equal to (lastAdj + tick
50 -- * n). That is because we do not abruptly adjust the clock skew instead
51 -- we adjust the tick size.
52 go lastAdj delay tick localTime n = do
53 action localTime
54 when (delay > 0) $ threadDelay delay
56 if n == freq
57 then do
58 (t, newTick, newDelay) <- adjustClock lastAdj localTime delay
59 go t newDelay newTick (localTime + newTick) 0
60 else go lastAdj delay tick (localTime + tick) (n + 1)
62 -- Adjust the tick size rather than the clock to avoid abrupt changes
63 -- resulting in jittery behavior at the end of every interval.
64 adjustClock lastAdj localTime delay = do
65 baseTime <- clock
66 let newTick = period + (baseTime - localTime) `div` freq
67 lastPeriod = (baseTime - lastAdj) `div` freq
68 newDelay = max 0 (delay + period - lastPeriod)
69 return (baseTime, newTick, newDelay)