Skip to content

Instantly share code, notes, and snippets.

@andytill
Created December 13, 2016 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andytill/4b888b10583ac2d1e97e5b2c8053d53e to your computer and use it in GitHub Desktop.
Save andytill/4b888b10583ac2d1e97e5b2c8053d53e to your computer and use it in GitHub Desktop.
%%
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