转载请注明,来自: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 ...