Add test cases for emqx_keepalive module (#2784)

* Improve the keepalive module
This commit is contained in:
Feng Lee 2019-08-16 18:24:39 +08:00 committed by turtleDeng
parent acf54509f5
commit d63eccd8b8
2 changed files with 22 additions and 16 deletions

View File

@ -25,14 +25,16 @@
-export_type([keepalive/0]). -export_type([keepalive/0]).
-record(keepalive, { -record(keepalive, {
statfun, statfun :: statfun(),
statval, statval :: integer(),
tsec, tsec :: pos_integer(),
tmsg, tmsg :: term(),
tref, tref :: reference(),
repeat = 0 repeat = 0 :: non_neg_integer()
}). }).
-type(statfun() :: fun(() -> {ok, integer()} | {error, term()})).
-opaque(keepalive() :: #keepalive{}). -opaque(keepalive() :: #keepalive{}).
%%-------------------------------------------------------------------- %%--------------------------------------------------------------------
@ -40,15 +42,17 @@
%%-------------------------------------------------------------------- %%--------------------------------------------------------------------
%% @doc Start a keepalive %% @doc Start a keepalive
-spec(start(fun(), integer(), any()) -> {ok, keepalive()} | {error, term()}). -spec(start(statfun(), pos_integer(), term())
start(_, 0, _) -> -> {ok, keepalive()} | {error, term()}).
{ok, #keepalive{}}; start(StatFun, TimeoutSec, TimeoutMsg) when TimeoutSec > 0 ->
start(StatFun, TimeoutSec, TimeoutMsg) ->
try StatFun() of try StatFun() of
{ok, StatVal} -> {ok, StatVal} ->
{ok, #keepalive{statfun = StatFun, statval = StatVal, TRef = timer(TimeoutSec, TimeoutMsg),
tsec = TimeoutSec, tmsg = TimeoutMsg, {ok, #keepalive{statfun = StatFun,
tref = timer(TimeoutSec, TimeoutMsg)}}; statval = StatVal,
tsec = TimeoutSec,
tmsg = TimeoutMsg,
tref = TRef}};
{error, Error} -> {error, Error} ->
{error, Error} {error, Error}
catch catch
@ -82,9 +86,7 @@ resume(KeepAlive = #keepalive{tsec = TimeoutSec, tmsg = TimeoutMsg}) ->
%% @doc Cancel Keepalive %% @doc Cancel Keepalive
-spec(cancel(keepalive()) -> ok). -spec(cancel(keepalive()) -> ok).
cancel(#keepalive{tref = TRef}) when is_reference(TRef) -> cancel(#keepalive{tref = TRef}) when is_reference(TRef) ->
catch erlang:cancel_timer(TRef), ok; catch erlang:cancel_timer(TRef), ok.
cancel(_) ->
ok.
timer(Secs, Msg) -> timer(Secs, Msg) ->
erlang:send_after(timer:seconds(Secs), self(), Msg). erlang:send_after(timer:seconds(Secs), self(), Msg).

View File

@ -35,3 +35,7 @@ keepalive_recv(KA, Acc) ->
after 4000 -> Acc after 4000 -> Acc
end. end.
t_cancel(_) ->
{ok, KA} = emqx_keepalive:start(fun() -> {ok, 1} end, 1, {keepalive, timeout}),
ok = emqx_keepalive:cancel(KA).