[erlang-questions] Erlang Scheduler for Recurring Events

Garrett Smith g@REDACTED
Wed Aug 24 15:59:08 CEST 2011

On Wed, Aug 24, 2011 at 6:51 AM, Hank Knight <hknight555@REDACTED> 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?

A super simple approach is to use one of the 'interval' functions in
the timer module.

But this can "pile up" requests if your work takes longer than the
interval. I personally don't like even the possibility of that, so I
use erlang:send_after/3 from within the working process.

Assuming you use a gen_server to perform the work, you can trigger
subsequent events without floating if you save your original "start"
time in state and use this algorithm to calculate value for Time in
the send_after call:

next_timer(#state{start=S, interval=I}) ->
    Now = timestamp(),
    ((Now - S) div I + 1) * I + S - Now.

The "now" timestamp is epoch milliseconds (also used to calculate Start):

timestamp() ->
    {M, S, U} = erlang:now(),
    M * 1000000000 + S * 1000 + U div 1000.

This approach prevents the pileup problem -- if your work takes longer
than interval, that period is simply skipped.

Of course if you don't care about regular intervals, you can track
your work time and subtract it from interval.


More information about the erlang-questions mailing list