Last active
February 19, 2016 14:04
-
-
Save vysakh0/864145abd80b1648c96f to your computer and use it in GitHub Desktop.
The Process that retries itself without monitor, supervisors.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Hydra do | |
use GenServer | |
def run(data) do | |
{:ok, pid} = GenServer.start(__MODULE__, data, []) | |
GenServer.cast(pid, :process) | |
end | |
def init(data) do | |
{:ok, data} | |
end | |
def process(pid) do | |
GenServer.cast(pid, :process) | |
end | |
def handle_cast(:process, {url, retry} = all) do | |
if retry !== 0, do: IO.puts "Retrying... #{retry} time" | |
url |> fetch_data |> save_data | |
{:noreply, all} | |
end | |
def terminate(:normal, _), do: nil | |
def terminate(:normal, {_url, 3}) do | |
IO.puts "Tried 3 times. No luck :( " | |
end | |
def terminate(_, {url, retry}) do | |
run({url, retry + 1}) | |
end | |
defp fetch_data(url) do | |
IO.puts "Requesting API for #{url}" | |
1/0 | |
"data" | |
end | |
defp save_data(data) do | |
IO.puts "Storing the data to remote database: #{data}" | |
Process.exit(self, :normal) | |
end | |
end | |
Hydra.run({"/api/users", 0}) | |
Hydra.run({"/api/posts", 0}) | |
Hydra.run({"/api/comments", 0}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment