[erlang-questions] Erlang Scheduler for Recurring Events

Garrett Smith <>
Wed Aug 24 16:32:27 CEST 2011


On Wed, Aug 24, 2011 at 9:23 AM, Daniel Luna <> wrote:
> On 24 August 2011 09:59, Garrett Smith <> wrote:
>> On Wed, Aug 24, 2011 at 6:51 AM, Hank Knight <> wrote:
>>> Hello,
>>>
>>> I need to scheduler a number of recurring events using Erlang.  Some
>>> events need to be triggered every second, some every three seconds and
>>> some every minute.  Any simple advise on how to do this or what tools
>>> to do?
> [cut away a good solution to the problem]
>> Of course if you don't care about regular intervals, you can track
>> your work time and subtract it from interval.
>
> If you don't care about exact regular intervals the easiest thing
> would be to use the timeout feature of gen_server.
>
> Initialize your gen_server with {ok, State, 3000} for a three second
> wait to the next event.  Add a handle_info(timeout, ...), and make
> sure that you set the timeout at every return point (i.e. {noreply,
> State, Timeout} for handle_info).
>
> This of course only works if the gen_server doesn't receive messages
> from elsewhere since then the timeout will never occur (it is a
> timeout after all).

I'd avoid timeouts for this case. They're really designed for a
different problem.

Plus handling 'timeout' as a message is weird when you probably want
something like 'do_some_work'.

I was told that the timeout=0 reply from init/1 is has some implicit
behavior that might be useful: it ensures that the
handle_info('timout', State) is called before any other messages can
be dispatched, which gives you a hook from init/1 that will run after
the call to gen_server:start_link has returned. Feels hacky, to me --
but the only way to handle certain cases.

Garrett



More information about the erlang-questions mailing list