您的位置:首页 > 移动开发

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

2011-07-04 01:18 399 查看
 转载请注明,来自: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 message
handle_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>}
tick
tick
tick
tick
tick
...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  server application io