When I rewrote Periodic Task System using Haskell, I couldn’t find a timer that was appropriate so I implemented one myself.

data Timer = Timer { waiter: :MVar()}

newTimer: :IO Timer
newTimer = Timer <$> newEmptyMVarCopy the code

Timer initializes an empty waiter

initTimer: :Timer -> IO() - >IO(a)initTimer (Timer{.. }) io =do 
  void $ forkIO $ forever $ do 
     takeMVar waiter 
     ioCopy the code

Initializing the Timer uses forever to cause the IO to go into an infinite loop and uses MVar to make the IO wait.

startTimer: :Timer -> Int -> IO(a)startTimer (Timer{.. }) delay =do 
  void $ forkIO $ do 
    threadDelay delay 
    putMVar waiter ()Copy the code

When the Timer starts, forkIO emits a thread. Use threadDelay to wait for the corresponding time to unlock the waiter

So a simple Timer comes out.

See timer.hs for the complete code

You are also welcome to Star Periodic Task System