<commit_before>module Hans.Timers (
    Milliseconds
  , Timer()
  , delay
  , delay_
  , cancel
  ) where

import Control.Concurrent (forkIO,ThreadId,threadDelay,killThread)


type Milliseconds = Int

newtype Timer = Timer ThreadId
                deriving (Show,Eq)

-- | Delay an action, giving back a handle to allow the timer to be cancelled.
delay :: Milliseconds -> IO () -> IO Timer
delay n body = Timer `fmap` forkIO (threadDelay (n * 1000) >> body)

-- | Delay an action.
delay_ :: Milliseconds -> IO () -> IO ()
delay_ n body =
  do _ <- forkIO (threadDelay (n * 1000) >> body)
     return ()

-- | Cancel a delayed action.
cancel :: Timer -> IO ()
cancel (Timer tid) = killThread tid<commit_msg>Add isCancelled to Hans.Timers<commit_after>module Hans.Timers (
    Milliseconds
  , Timer()
  , delay
  , delay_
  , cancel
  , isCancelled
  ) where

import Control.Concurrent (forkIO,ThreadId,threadDelay,killThread
                          ,mkWeakThreadId)
import GHC.Conc (threadStatus,ThreadStatus(..))
import System.Mem.Weak (Weak,deRefWeak)


type Milliseconds = Int

-- | A handle to a scheduled timer.
--
-- NOTE: This keeps a weak reference to the thread containing the timer, to
-- allow it to still receive exceptions (see mkWeakThreadId).
newtype Timer = Timer (Weak ThreadId)

-- | Delay an action, giving back a handle to allow the timer to be cancelled.
delay :: Milliseconds -> IO () -> IO Timer
delay n body =
  do tid <- forkIO (threadDelay (n * 1000) >> body)
     wid <- mkWeakThreadId tid
     return (Timer wid)

-- | Delay an action.
delay_ :: Milliseconds -> IO () -> IO ()
delay_ n body =
  do _ <- forkIO (threadDelay (n * 1000) >> body)
     return ()

-- | Cancel a delayed action.
cancel :: Timer -> IO ()
cancel (Timer wid) =
  do mb <- deRefWeak wid
     case mb of
       Just tid -> killThread tid
       Nothing  -> return ()

isCancelled :: Timer -> IO Bool
isCancelled (Timer wid) =
  do mb <- deRefWeak wid
     case mb of
       Just tid -> do status <- threadStatus tid
                      case status of
                        ThreadRunning   -> return False
                        ThreadBlocked _ -> return False
                        _               -> return True

       Nothing  -> return True
{'fraction_non_alphanumeric': 0.1033717834960071, 'fraction_numerical': 0.00709849157054126, 'mean_word_length': 2.3656716417910446, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '67700', 'n_tokens_mistral': 704, 'n_tokens_neox': 648, 'n_words': 243}