erlang的timer定时器浅析

  timer作为其计时器:

     erlang的计时器timer是通过一个唯一的timer进程实现的,该进程是一个gen_server,用户通过timer:send_after和timer:apply_after在指定时间间隔后收到指定消息或执行某个函数,每个用户的计时器都是一条记录,保存在timer的ets表timer_tab中,timer的时序驱动通过gen_server的超时机制实现。若同时使用timer的用户过多,则timer将响应不过来,成为瓶颈。

     更好的方法是使用erlang的原生计时器erlang:send_after和erlang:start_timer,它们把计时器附着在进程自己身上。

看了段timer的源码,如下:

schedule_cast(Msg, Default, Timers) ->
    %% Cancel the old timer...
    TRef = proplists:get_value(Msg, Timers),
    timer:cancel(TRef),

    %% Lookup the interval...
    IntervalKey = list_to_atom(atom_to_list(Msg) ++ "_interval"),
    Interval = sync_utils:get_env(IntervalKey, Default),

    %% Schedule the call...
    {ok, NewTRef} = timer:apply_after(Interval, gen_server, cast, [?SERVER, Msg]),

    %% Return the new timers structure...
    lists:keystore(Msg, 1, Timers, {Msg, NewTRef}).

这里的 timer:apply_after/4 这里为什么要这么写?  timer:apply_after(Time, Module, Function, Arguments) -> {ok, TRef} | {error, Reason}

没有去调用timer:send_after   查看API后,apply_after是函数形式,send_after是发消息,查看timer的源码之后,发现send_after就是调用apply_after,只是两种写法罢了。

timer的源码链接:见 https://github.com/zhongwencool/otp/blob/maint/lib/stdlib/src/timer.erl

从学贵有恒的博客中,看到了下面的图:
这是根据timer源码,画的流程图

timer的进程都是通过一个唯一的timer进程实现的,该进程是一个gen_server。建议使用erlang::send_after和erlang:start_timer,它们把计时器附着在进程自己身上.

 

转载于:https://www.cnblogs.com/unqiang/p/4095509.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值