7

I have small program that need to be executed every 5 minutes.

For now, I have shell script that perform that task, but I want to provide for user ability to run it without additional scripts via key in CLI.

What is the best way to achieve this?

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
Filip van Hoft
  • 301
  • 1
  • 7

1 Answers1

9

I presume you'll want something like that (more or less pseudocode):

import Control.Concurrent (forkIO, threadDelay)
import Data.IORef
import Control.Monad (forever)

main = do
    var <- newIORef 5000
    forkIO (forever $ process var)
    forever $ readInput var

process var = do
    doActualProcessing

    interval <- readIORef var
    _ <- threadDelay interval

readInput var = do
    newInterval <- readLn
    writeIORef var newInterval

If you need to pass some more complex data from the input thread to the processing thread, MVars or TVars could be a better choice than IORefs.

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
  • thanks! That is what I was looking for, I didn't know about `forever` – Filip van Hoft Oct 13 '15 at 12:10
  • @FilipvanHoft forever's implementation is pretty straighforward, but just calling e.g. `process var` at the end of `process` would make it infinitely recursive (thus looped) as well. – Bartek Banachewicz Oct 13 '15 at 12:32
  • 1
    Any reasons for choosing `TVar`s instead of, say, `IORef`s ? Is there some atomicity issue in the code above? – chi Oct 13 '15 at 13:23
  • 1
    @chi I plainly forgot about them. I almost never use "raw" `IORef`s, but of course the code shown has no possible races. I'll edit it. – Bartek Banachewicz Oct 13 '15 at 13:30
  • 1
    I'm not sure why you'd use an `IORef` or a `TVar` at all. Just pass `5000` to process directly, – Rein Henrichs Oct 13 '15 at 15:53
  • @ReinHenrichs And how do you propose the changed value of the interval is propagated to the process thread then? – Bartek Banachewicz Oct 13 '15 at 16:10
  • I don't see a requirement to do so. OP said "CLI is set at first run", which I take to mean that the timeout value does not need to be changed after the program starts. – Rein Henrichs Oct 13 '15 at 16:16
  • @ReinHenrichs it's in the comments. – Bartek Banachewicz Oct 13 '15 at 16:18
  • @BartekBanachewicz Can you be specific? I don't see any comment to that effect but I see multiple comments that indicate otherwise, like "./app -e -t 5 , e key for endless run, t- time interval " where it is set via a command line flag. In fact, I see you suggesting it and OP disagreeing with you. – Rein Henrichs Oct 13 '15 at 16:19