How to perform actions periodically with Erlang's gen_server?

前端 未结 4 798
伪装坚强ぢ
伪装坚强ぢ 2020-12-23 20:32

I want to start a gen_server that additionally, will perform one action every minute.

What is the best way to schedule that?

4条回答
  •  旧时难觅i
    2020-12-23 20:52

    There is actually a built-in mechanism within gen_server to accomplish the same thing. If the third element of response tuple of the init, handle_call, handle_cast or handle_info methods in the gen_server is an integer, a timeout message wil be sent to the process after that period of time in millisecs... which should be handled using handle_info. For eg :

    init(Args) ->
       ... % Start first timer
       {ok, SomeState, 20000}. %% 20000 is the timeout interval
    
    handle_call(Input, From, State) ->
       ... % Do something
       ... % Do something else
       {reply, SomeState, 20000}. %% 20000 is the timeout interval
    
    handle_cast(Input, State) ->
       ... % Do something
       ... % Do something else
       {noreply, SomeState, 20000}. %% 20000 is the timeout interval
    
    
    %% A timeout message is sent to the gen_server to be handled in handle_info %%
    handle_info(timeout, State) ->
       ... % Do the action
       ... % Start new timer
       {noreply, SomeState, 20000}. %% "timeout" can be sent again after 20000 ms
    
    

提交回复
热议问题