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

来源:互联网 发布:oracle数据库管理规范 编辑:程序博客网 时间:2024/05/22 15:08

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

使用erlang:send_after()函数,代码如下:

-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]).-define(INTERVAL, 5000).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]),    erlang:send_after(?INTERVAL, self(), {trigger, 0}),    {ok, 0}.handle_call(_Msg, _From, State) ->     {noreply, State}.handle_cast(_Msg, State)  -> {noreply, State}.handle_info({trigger, N}, State)  -> io:format("tick ~p~n", [N]),erlang:send_after(?INTERVAL, self(), {trigger, N+1}),{noreply, State}.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 0tick 1tick 2tick 3tick 4tick 5tick 6tick 7tick 8tick 9tick 10...