timer cleanup in case gen_server crashes

Tony Rogvall <>
Fri Sep 3 12:43:06 CEST 2004

On Fri, 2004-09-03 at 03:12, Reto Kramer wrote:
> If I start an interval timer in the init function of a gen_server like 
> this:
> init([]) ->
>      process_flag(trap_exit, true),
>      {ok, TRef} = timer:apply_interval(get_period(),
> 				      ?MODULE, trigger_heartbeat, []),
>      {ok, #state{..., send_timer=TRef, ...}}.
> How can I then make sure that the timer is canceled in case the 
> gen_server itself crashes?

The timer module will take care of that.

> Will this happen automatically because the gen_server process is the 
> parent of whatever the timer module spawns?
The timer server will set a link to your server.
And clean up.

> I don't want to have the supervisor that starts my gen_server to know 
> about the timer, I view the timer as an implementation detail of what 
> the gen_server does. Would erlang gurus say this is reasonable?
I think that the timer bifs are better and more light weight

Ref = erlang:set_timer(AfterMilli, Pid, Term) or
Ref = erlang:send_after(AfterMilli, Pid, Message)

They however must be cleaned up in the terminate function.
This is a place for emulator improvement, that is to associate
all timers with the receiving process and clean them automatically
when that process dies (no point sending timeout to a dead process!)

Thanks for pointing that out (indirectly :-)


More information about the erlang-questions mailing list