Kshitij Mittal
Kshitij Mittal

Reputation: 2776

Loop in elixir with delay interval

I have the following code in elixir, where I want to call a function - parseCsvFiles in a loop:

def loopParseFiles do
    spawn(Parse_Csv,:parseCsvFiles,[self])
    receive do
        {:parse_complete} -> loopParseFiles
        after
         20000 -> loopParseFiles
    end
end

In the above code, I want to set a delay such that, the loopParseFiles function is called back after 20000 miliseconds or after :parse_complete is received - whichever is more.

TIA :)

Upvotes: 1

Views: 1815

Answers (1)

legoscia
legoscia

Reputation: 41598

So you want to always wait for at least 20 seconds, and then wait until :parse_complete is received? You can do it like this:

def loopParseFiles do
    spawn(Parse_Csv,:parseCsvFiles,[self])
    :timer.sleep 20000
    receive do
        {:parse_complete} -> loopParseFiles
    end
end

Even if the :parse_complete message arrives during the call to :timer.sleep, it will still be waiting in the mailbox once the receive expression is ready to pick it up.

Upvotes: 2

Related Questions