开发者

Allowing a gen_fsm to timeout if it receives no messages

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 th开发者_JAVA百科em 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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜