Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Write stdin to a file and rewrite the file after a timeout
-- See
-- usage: rewrite-after-timeout SECONDS FILENAME
import Prelude
import System.IO
import System.Timeout
import System.Environment
import Data.Time
import Data.Maybe
import Control.Monad
main :: IO ()
main = do
pause <- read . head <$> getArgs :: IO Integer
filename <- head . tail <$> getArgs :: IO String
start <- getCurrentTime
getLineAndAppendOrReplace pause filename start
getLineAndAppendOrReplace :: Integer -> FilePath -> UTCTime -> IO ()
getLineAndAppendOrReplace pause filename lastAppend = do
maybeLine <- timeout 100000 getLine -- timeout in microseconds
time <- case maybeLine of
Just line -> appendLine pause filename lastAppend line
Nothing -> pure lastAppend
getLineAndAppendOrReplace pause filename time
appendLine :: Integer -> FilePath -> UTCTime -> String -> IO UTCTime
appendLine pause filename lastAppend line = do
now <- getCurrentTime
let mode = if diffUTCTime now lastAppend > realToFrac pause
then WriteMode
else AppendMode
file <- openFile filename mode
hPutStrLn file line
hClose file
pure now
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment