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

本文介绍了一个使用Erlang OTP框架中的gen_server行为实现的简单定时器示例。该示例展示了如何设置周期性的超时,并在超时发生时向进程发送消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载请注明,来自:http://blog.youkuaiyun.com/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
...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值