Skip to content

Commit

Permalink
Refactor funbox_utimer
Browse files Browse the repository at this point in the history
  • Loading branch information
dmitrivereshchagin committed Jul 21, 2024
1 parent a6f45ef commit edb2846
Showing 1 changed file with 16 additions and 14 deletions.
30 changes: 16 additions & 14 deletions src/funbox_utimer.erl
Original file line number Diff line number Diff line change
@@ -1,39 +1,41 @@
-module(funbox_utimer).

%% API
-export([sleep/1]).
-export([seconds/1]).
-export([sleep/1]).

%%%===================================================================
%%% API
%%%===================================================================

-spec sleep(non_neg_integer()) -> ok.
sleep(Time) when is_integer(Time), Time >= 2000 ->
{ElapsedTime, _} = timer:tc(timer, sleep, [Time div 1000 - 1]),
sleep(Time - ElapsedTime, monotonic_time());
sleep(Time) when is_integer(Time), Time >= 0 ->
sleep(Time, monotonic_time()).

-spec seconds(Seconds) -> MicroSeconds when
Seconds :: non_neg_integer(),
MicroSeconds :: non_neg_integer().
seconds(Seconds) ->
1000 * 1000 * Seconds.

-spec sleep(non_neg_integer()) -> ok.
sleep(Time) when is_integer(Time), Time >= 2000 ->
Deadline = monotonic_time() + Time,
timer:sleep(Time div 1000 - 1),
sleep_until(Deadline);
sleep(Time) when is_integer(Time), Time >= 0 ->
sleep_until(monotonic_time() + Time).

%%%===================================================================
%%% Internal functions
%%%===================================================================

-spec sleep(non_neg_integer(), integer()) -> ok.
sleep(Time, Start) ->
case monotonic_time() of
Now when Now - Start < Time ->
sleep(Time, Start);
_ ->
-spec sleep_until(integer()) -> ok.
sleep_until(Deadline) ->
case monotonic_time() < Deadline of
true ->
sleep_until(Deadline);
false ->
ok
end.

-compile({inline, [monotonic_time/0]}).
-spec monotonic_time() -> integer().
monotonic_time() ->
erlang:monotonic_time(microsecond).

0 comments on commit edb2846

Please sign in to comment.