First off, I'm very new to Elixir so this may be a misguided question
I have a function that launches two processes.
The first process uses the erlang :fs library to watch a directory for file changes and then sends a message to the second process.
The second process waits for a message that a file in a directory has changed and when it gets the message, runs a function that regenerates an HTML report (it's an invoice).
It looks like this:
def run_report_daemon(line_item_dir) do
if Process.whereis(:html_daemon) == nil do
spawn(HTMLInvoiceDaemon, :run_daemon, [line_item_dir])
|> Process.register(:html_daemon)
end
if Process.whereis(:file_watcher) == nil do
:fs.start_link(:file_watcher, Path.absname(line_item_dir))
end
Process.sleep(1000)
run_report_daemon(line_item_dir)
end
This "works" but what bothers me is the "sleep" and the recursive call.
My question: Is there a better way to keep the process containing the function that spawns my processes alive. Without the recursive call and the sleep it just dies and takes the other processes with it. With the recursive call and no sleep, it consumes a huge chunk of processor resources because it keeps looping very quickly.
The if blocks are necessary because otherwise it would repeatedly spawn and register the processes.
I thought of using Supervisor, but then I'm not sure how to launch the :fs process under a supervisor, and even in that case I need to keep the starting process alive.
I suspect my problem is because of a fundamental misunderstanding of "the right way to do things" in Elixir.
(note: I can probably do the whole thing without spawning processes like this, but it's a learning exercise)
HTMLInvoiceDaemon
? Can you post some more code? – Dogbertline_item_dir
arbitrary or do you know these at start-time? Also, how many of them are there? I had attempted to answer but then realized that the input there would be tough to get if it's not known when the application starts up. – Dave Lugg