views:

70

answers:

1

Normally if I'd like to have an Erlang process timeout I would use the following construct:

receive 
    Msg -> ok; %% handle message
after 60000 ->
    %% Handle timeout and exit
end.

Is there a similar mechanism in the OTP servers such as gen_fsm? I will be spawning gen_fsm's for each active session with my application, and would like to have them exit if a timeout value for inactivity is exceeded after receiving a message.

I can write my own custom process if need be, but would prefer to use a gen_fsm if possible.

+9  A: 

I dug some more and found the answer to my own question.

There is an optional fourth argument in message handler "Result"s that you can use which is a timeout.

so:

some_fsm_state({set, Val}, State) ->
    NewState = do(Val, State),
    {next_state, another_fsm_state, NewState, 5000};

another_fsm_state(timeout, State) ->
    handle_timeout(State).

another_fsm_state({set, Val}, State) ->
    %% more code that handles this state.

Once some_fsm_state is called, it transitions to the next state of "another_fsm_state" with a timeout of 5000ms. If not new message is received within 5000ms, then another_fsm_state(timeout, State) is called.

Clever OTP programmers. :)

It should be noted that this fourth element in the Results tuple can be hibernate. Please see Erlang documentation for more information.

Erlang - Hibernate

gen_fsm docs

Jeff Thompson
Also you can set the initial timeout, if you pass a `{timeout, Time}` option when calling start.
Zed
Excellent, thank you Zed!
Jeff Thompson