I want to start a gen_server that additionally, will perform one action every minute.
What is the best way to schedule that?
I want to start a gen_server that additionally, will perform one action every minute.
What is the best way to schedule that?
You have two easy alternatives, use
timer:send_interval/2
orerlang:send_after/3
.send_interval
is easier to setup, whilesend_after
(when used in the Erlang module) is more reliable since it is a built-in function, see the Efficiency Guide.Using
send_after
also ensures that thegen_server
process is not overloaded. If you were using thesend_interval
function you would get a message regardless if the process can keep up or not. Withsend_after
being called just before the return inhandle_info
you only schedule a new message once you handled the previous one. If you want more accurate time tracking you can still schedule asend_after
with the time set dynamically to something lower than?INTERVAL
(or even 0) to catch up.I would recommend something along the following lines in your
gen_server
:Instead of
trigger
you could send something with a state if it is needed, like{trigger, Count}
or something.To precisely control the timer, you may want to use
erlang:start_timer
, and save each timer reference you have created.erlang:start_timer
has a tiny difference witherlang:send_after
, see http://www.erlang.org/doc/man/erlang.html#start_timer-3 and http://www.erlang.org/doc/man/erlang.html#send_after-3Example use case:
There is also the
timer
module, which could be used.http://erldocs.com/R14B02/stdlib/timer.html?i=8&search=timer#cancel_timer/1
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, atimeout
message wil be sent to the process after that period of time in millisecs... which should be handled using handle_info. For eg :