Skip to content

Instantly share code, notes, and snippets.

@schoettl
Last active January 23, 2017 16:01
Show Gist options
  • Save schoettl/312467a7fb6ad27c0ab74cbebbc30aac to your computer and use it in GitHub Desktop.
Save schoettl/312467a7fb6ad27c0ab74cbebbc30aac to your computer and use it in GitHub Desktop.
Write stdin to a file and rewrite the file after a timeout
-- See http://jakob.keramik-schoettl.de/blog/
-- 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