[erlang-questions] gen_server Question

Geoff Cant <>
Sun Aug 1 03:51:50 CEST 2010


gen_server has exactly the functionality you need. When returning from a
callback, you can specify an extra timeout duration -- instead of
{noreply, State}, use {noreply, State,
timer:seconds(Timeout)}. After Timeout seconds of inactivity (this
timer is cancelled every time you enter a callback), you'll enter the
handle_info callback as: handle_info('timeout', State).

The only thing you need to keep in mind with this approach is that all
your callback return tuples should include this timeout
(init/call/cast/info). This approach works well if you want to ensure
you wait at least Timeout seconds between each timeout. If you take a
long time to process a timeout, the next one will occur that much later
as the clock starts from when you return from the callback.

The other main approach is timer:send_interval/2 - this requires no
modification of your gen_server return tuples, and will be sent every
Interval, no matter how long it takes you to process one. It's useful if
you need to do something every Interval and doing a few in a row is fine
if the system slows down for some reason. One problem I have with it is
I do development on my laptop, and when it wakes from sleep you get a
barrage of timeouts.

Being something of an OTP zealot, I'd advise you to use the gen_server
behaviour unless you've got a good reason not to.

Cheers,
-Geoff

"Behdad Forghani" <> writes:

> Hello,
>
>  
>
> I am writing a module that mostly monitors a directory at certain intervals
> and processes the files that are dropped into that directory and sends
> messages to another process. I want this processes to be supervised. Two
> options come into my mind:
>
>  
>
> 1 - Write a server myself, similar to server4.erl in Joe Armstrong's
> "Programming Erlang" book. In this case, I will use an "after Time ->"
> clause.
>
> 2 - Use gen_server behavior and use timer module to send messages to myself,
> since, I do not see any other way to get regular timeouts.
>
>  
>
> My question is, shall I try to use gen_server? Do I get anything extra by
> using gen_server? I do not need multicall and I can write my own terminate
> routine. Is there anything else that I will be missing?
>
>  
>
> Thanks in advance.
>
> Behdad
>
>  
>

-- 
Geoff Cant


More information about the erlang-questions mailing list