在gen_server中实现定时功能(方法二)

来源:互联网 发布:二维码扫描 java sdk 编辑:程序博客网 时间:2024/06/14 08:32

 转载请注明,来自:http://blog.csdn.net/skyman_2001

在gen_server的init、handle_call、handle_cast 或handle_info函数里的返回元祖的第3个元素是个整数,代表timeout的间隔(单位为ms),则时间到时会发送timeout消息给进程,该消息通过handle_info()来处理。

代码如下:

-module(otp_test).-behaviour(gen_server).-export([start_link/0]).%% gen_server callbacks-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).start_link() ->    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).init([]) ->    %% Note we must set trap_exit = true if we     %% want terminate/2 to be called when the application    %% is stopped    process_flag(trap_exit, true),    io:format("~p starting~n",[?MODULE]),    {ok, state, 5000}. % 5000是timeout间隔handle_call(_Msg, _From, State) ->     {noreply, State, 5000}. handle_cast(_Msg, State)  ->     {noreply, State, 5000}.%% handle timeout messagehandle_info(timeout, State)  -> io:format("tick~n",[]),{noreply, State, 5000}.terminate(_Reason, _State) ->     io:format("~p stopping~n",[?MODULE]),    ok.code_change(_OldVsn, State, _Extra) -> {ok, State}.


运行:

otp_test:start_link().


结果:

otp_test starting  {ok,<0.59.0>}  tickticktickticktick...
原创粉丝点击