zoukankan      html  css  js  c++  java
  • 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,它们把计时器附着在进程自己身上.

    
    
  • 相关阅读:
    直方图内最大矩阵
    P1578 奶牛浴场
    P1569 [USACO11FEB]属牛的抗议Generic Cow Prote…
    P1566 加等式
    P1564 膜拜
    P1541 乌龟棋
    P1537 弹珠
    Response.AddHeader使用实例
    LSPCI具体解释分析
    介绍一款开源的类Excel电子表格软件
  • 原文地址:https://www.cnblogs.com/unqiang/p/4095509.html
Copyright © 2011-2022 走看看