I would like to implement a simple timer that I can
- exit at any time and get result
- run any number of times.
I come up with timer1 implementation. It satisfies (2) and almost satisfies (1) since it has to wait until threadDelay finishes. Any pointer would be appreciated.
ps. The another implementation with catch exception handling I have tried exits immediately but cannot exit via SIGINT twice or else the program will be terminated.
timer1 :: MVar () -> Int -> IO Int
timer1 v sec = do
putStrLn (show sec)
threadDelay 1000000
tryTakeMVar v >>= \case
Just _ -> return sec
Nothing -> exitCond
where
exitCond = if sec > 0 then timer1 v (sec - 1) else return 0
main :: IO ()
main = do
v <- newEmptyMVar
installHandler sigINT (CatchOnce $ putMVar v ()) Nothing
res <- timer1 v 5
putStrLn $ "timer1: " ++ show res
v <- newEmptyMVar
installHandler sigINT (CatchOnce $ putMVar v ()) Nothing
res <- timer1 v 5
putStrLn $ "timer1: " ++ show res