Skip to content

Instantly share code, notes, and snippets.

@andytill andytill/retry.erl
Created Dec 13, 2016

Embed
What would you like to do?
%%
retry_delayed(Fn, DelayMs, TotalElapsedMs) when is_function(Fn),
is_integer(DelayMs),
is_integer(TotalElapsedMs),
TotalElapsedMs > DelayMs ->
retry_delayed2(Fn, DelayMs, TotalElapsedMs, ordsets:new()).
retry_delayed2(Fn, DelayMs, TotalElapsedMs1, Errors1) ->
NowStart = now_ms(),
case Fn() of
Result when Result == ok orelse (is_tuple(Result) andalso element(1, Result) == ok) ->
Result;
Error ->
Errors2 = ordsets:add_element(Error, Errors1),
Elapsed = now_ms() - NowStart,
TotalElapsedMs2 = TotalElapsedMs1 - Elapsed,
case TotalElapsedMs2 =< 0 of
true ->
{error, ordsets:to_list(Errors2)};
false ->
timer:sleep(DelayMs),
retry_delayed2(Fn, DelayMs, TotalElapsedMs2-DelayMs, Errors2)
end
end.
now_ms() ->
{Megasecs, Secs, Microsecs} = erlang:now(),
(Megasecs*1000000000) + (Secs*1000) + (Microsecs div 1000).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.