1gen_statem(3) Erlang Module Definition gen_statem(3)
2
3
4
6 gen_statem - Generic state machine behavior.
7
9 gen_statem provides a generic state machine behaviour that for new code
10 replaces its predecessor gen_fsm since Erlang/OTP 20.0. The gen_fsm be‐
11 haviour remains in OTP "as is".
12
13 Note:
14 If you are new to gen_statem and want an overview of concepts and oper‐
15 ation the section gen_statem Behaviour located in the User's Guide
16 OTP Design Principles is recommended to read before this reference
17 manual, possibly after the Description section you are reading here.
18
19
20 This reference manual contains type descriptions generated from types
21 in the gen_statem source code, so they are correct. However, the gener‐
22 ated descriptions also reflect the type hierarchy, which sometimes
23 makes it hard to get a good overview. If so, see the section gen_statem
24 Behaviour in the OTP Design Principles User's Guide.
25
26 Note:
27
28 * This behavior appeared in Erlang/OTP 19.0.
29
30 *
31 In OTP 19.1 a backwards incompatible change of the return tuple
32 from Module:init/1 was made and the mandatory callback function
33 Module:callback_mode/0 was introduced.
34
35 *
36 In OTP 20.0 generic time-outs were added.
37
38 *
39 In OTP 22.1 time-out content update and explicit time-out cancel
40 were added.
41
42 gen_statem has got the same features that gen_fsm had and adds some
43 really useful:
44
45 * Co-located state code
46
47 * Arbitrary term state
48
49 * Event postponing
50
51 * Self-generated events
52
53 * State time-out
54
55 * Multiple generic named time-outs
56
57 * Absolute time-out time
58
59 * Automatic state enter calls
60
61 *
62 Reply from other state than the request, sys traceable
63
64 * Multiple sys traceable replies
65
66 Two callback modes are supported:
67
68 * One for finite-state machines (gen_fsm like), which requires the
69 state to be an atom and uses that state as the name of the current
70 callback function
71
72 * One without restriction on the state data type that uses one call‐
73 back function for all states
74
75 The callback model(s) for gen_statem differs from the one for gen_fsm,
76 but it is still fairly easy to rewrite from gen_fsm to gen_statem.
77
78 A generic state machine process (gen_statem) implemented using this
79 module has a standard set of interface functions and includes function‐
80 ality for tracing and error reporting. It also fits into an OTP super‐
81 vision tree. For more information, see OTP Design Principles.
82
83 A gen_statem assumes all specific parts to be located in a callback
84 module exporting a predefined set of functions. The relationship
85 between the behavior functions and the callback functions is as fol‐
86 lows:
87
88 gen_statem module Callback module
89 ----------------- ---------------
90 gen_statem:start
91 gen_statem:start_link -----> Module:init/1
92
93 Server start or code change
94 -----> Module:callback_mode/0
95
96 gen_statem:stop -----> Module:terminate/3
97
98 gen_statem:call
99 gen_statem:cast
100 erlang:send
101 erlang:'!' -----> Module:StateName/3
102 Module:handle_event/4
103
104 - -----> Module:terminate/3
105
106 - -----> Module:code_change/4
107
108 Events are of different types, so the callback functions can know the
109 origin of an event and how to respond.
110
111 If a callback function fails or returns a bad value, the gen_statem
112 terminates, unless otherwise stated. However, an exception of class
113 throw is not regarded as an error but as a valid return from all call‐
114 back functions.
115
116 The state callback for a specific state in a gen_statem is the callback
117 function that is called for all events in this state. It is selected
118 depending on which callback mode that the callback module defines with
119 the callback function Module:callback_mode/0.
120
121 When the callback mode is state_functions, the state must be an atom
122 and is used as the state callback name; see Module:StateName/3. This
123 co-locates all code for a specific state in one function as the
124 gen_statem engine branches depending on state name. Note the fact that
125 the callback function Module:terminate/3 makes the state name terminate
126 unusable in this mode.
127
128 When the callback mode is handle_event_function, the state can be any
129 term and the state callback name is Module:handle_event/4. This makes
130 it easy to branch depending on state or event as you desire. Be careful
131 about which events you handle in which states so that you do not acci‐
132 dentally postpone an event forever creating an infinite busy loop.
133
134 When gen_statem receives a process message it is converted into an
135 event and the state callback is called with the event as two arguments:
136 type and content. When the state callback has processed the event it
137 returns to gen_statem which does a state transition. If this state
138 transition is to a different state, that is: NextState =/= State, it is
139 a state change.
140
141 The state callback may return transition actions for gen_statem to exe‐
142 cute during the state transition, for example to reply to a
143 gen_statem:call/2,3.
144
145 One of the possible transition actions is to postpone the current
146 event. Then it is not retried in the current state. The gen_statem
147 engine keeps a queue of events divided into the postponed events and
148 the events still to process. After a state change the queue restarts
149 with the postponed events.
150
151 The gen_statem event queue model is sufficient to emulate the normal
152 process message queue with selective receive. Postponing an event cor‐
153 responds to not matching it in a receive statement, and changing states
154 corresponds to entering a new receive statement.
155
156 The state callback can insert events using the transition actions
157 next_event and such an event is inserted in the event queue as the next
158 to call the state callback with. That is, as if it is the oldest incom‐
159 ing event. A dedicated event_type() internal can be used for such
160 events making them impossible to mistake for external events.
161
162 Inserting an event replaces the trick of calling your own state han‐
163 dling functions that you often would have to resort to in, for example,
164 gen_fsm to force processing an inserted event before others.
165
166 The gen_statem engine can automatically make a specialized call to the
167 state callback whenever a new state is entered; see state_enter(). This
168 is for writing code common to all state entries. Another way to do it
169 is to explicitly insert an event at the state transition, and/or to use
170 a dedicated state transition function, but that is something you will
171 have to remember at every state transition to the state(s) that need
172 it.
173
174 Note:
175 If you in gen_statem, for example, postpone an event in one state and
176 then call another state callback of yours, you have not done a state
177 change and hence the postponed event is not retried, which is logical
178 but can be confusing.
179
180
181 For the details of a state transition, see type transition_option().
182
183 A gen_statem handles system messages as described in sys. The sys mod‐
184 ule can be used for debugging a gen_statem.
185
186 Notice that a gen_statem does not trap exit signals automatically, this
187 must be explicitly initiated in the callback module (by calling
188 process_flag(trap_exit, true).
189
190 Unless otherwise stated, all functions in this module fail if the spec‐
191 ified gen_statem does not exist or if bad arguments are specified.
192
193 The gen_statem process can go into hibernation; see proc_lib:hiber‐
194 nate/3. It is done when a state callback or Module:init/1 specifies
195 hibernate in the returned Actions list. This feature can be useful to
196 reclaim process heap memory while the server is expected to be idle for
197 a long time. However, use this feature with care, as hibernation can be
198 too costly to use after every event; see erlang:hibernate/3.
199
200 There is also a server start option {hibernate_after, Timeout} for
201 start/3,4, start_link/3,4 or enter_loop/4,5,6, that may be used to
202 automatically hibernate the server.
203
205 The following example shows a simple pushbutton model for a toggling
206 pushbutton implemented with callback mode state_functions. You can push
207 the button and it replies if it went on or off, and you can ask for a
208 count of how many times it has been pushed to switch on.
209
210 The following is the complete callback module file pushbutton.erl:
211
212 -module(pushbutton).
213 -behaviour(gen_statem).
214
215 -export([start/0,push/0,get_count/0,stop/0]).
216 -export([terminate/3,code_change/4,init/1,callback_mode/0]).
217 -export([on/3,off/3]).
218
219 name() -> pushbutton_statem. % The registered server name
220
221 %% API. This example uses a registered name name()
222 %% and does not link to the caller.
223 start() ->
224 gen_statem:start({local,name()}, ?MODULE, [], []).
225 push() ->
226 gen_statem:call(name(), push).
227 get_count() ->
228 gen_statem:call(name(), get_count).
229 stop() ->
230 gen_statem:stop(name()).
231
232 %% Mandatory callback functions
233 terminate(_Reason, _State, _Data) ->
234 void.
235 code_change(_Vsn, State, Data, _Extra) ->
236 {ok,State,Data}.
237 init([]) ->
238 %% Set the initial state + data. Data is used only as a counter.
239 State = off, Data = 0,
240 {ok,State,Data}.
241 callback_mode() -> state_functions.
242
243 %%% state callback(s)
244
245 off({call,From}, push, Data) ->
246 %% Go to 'on', increment count and reply
247 %% that the resulting status is 'on'
248 {next_state,on,Data+1,[{reply,From,on}]};
249 off(EventType, EventContent, Data) ->
250 handle_event(EventType, EventContent, Data).
251
252 on({call,From}, push, Data) ->
253 %% Go to 'off' and reply that the resulting status is 'off'
254 {next_state,off,Data,[{reply,From,off}]};
255 on(EventType, EventContent, Data) ->
256 handle_event(EventType, EventContent, Data).
257
258 %% Handle events common to all states
259 handle_event({call,From}, get_count, Data) ->
260 %% Reply with the current count
261 {keep_state,Data,[{reply,From,Data}]};
262 handle_event(_, _, Data) ->
263 %% Ignore all other events
264 {keep_state,Data}.
265
266
267 The following is a shell session when running it:
268
269 1> pushbutton:start().
270 {ok,<0.36.0>}
271 2> pushbutton:get_count().
272 0
273 3> pushbutton:push().
274 on
275 4> pushbutton:get_count().
276 1
277 5> pushbutton:push().
278 off
279 6> pushbutton:get_count().
280 1
281 7> pushbutton:stop().
282 ok
283 8> pushbutton:push().
284 ** exception exit: {noproc,{gen_statem,call,[pushbutton_statem,push,infinity]}}
285 in function gen:do_for_proc/2 (gen.erl, line 261)
286 in call from gen_statem:call/3 (gen_statem.erl, line 386)
287
288
289 To compare styles, here follows the same example using callback mode
290 handle_event_function, or rather the code to replace after function
291 init/1 of the pushbutton.erl example file above:
292
293 callback_mode() -> handle_event_function.
294
295 %%% state callback(s)
296
297 handle_event({call,From}, push, off, Data) ->
298 %% Go to 'on', increment count and reply
299 %% that the resulting status is 'on'
300 {next_state,on,Data+1,[{reply,From,on}]};
301 handle_event({call,From}, push, on, Data) ->
302 %% Go to 'off' and reply that the resulting status is 'off'
303 {next_state,off,Data,[{reply,From,off}]};
304 %%
305 %% Event handling common to all states
306 handle_event({call,From}, get_count, State, Data) ->
307 %% Reply with the current count
308 {next_state,State,Data,[{reply,From,Data}]};
309 handle_event(_, _, State, Data) ->
310 %% Ignore all other events
311 {next_state,State,Data}.
312
313
315 server_name() =
316 {global, GlobalName :: term()} |
317 {via, RegMod :: module(), Name :: term()} |
318 {local, atom()}
319
320 Name specification to use when starting a gen_statem server. See
321 start_link/3 and server_ref() below.
322
323 server_ref() =
324 pid() |
325 (LocalName :: atom()) |
326 {Name :: atom(), Node :: atom()} |
327 {global, GlobalName :: term()} |
328 {via, RegMod :: module(), ViaName :: term()}
329
330 Server specification to use when addressing a gen_statem server.
331 See call/2 and server_name() above.
332
333 It can be:
334
335 pid() | LocalName:
336 The gen_statem is locally registered.
337
338 {Name,Node}:
339 The gen_statem is locally registered on another node.
340
341 {global,GlobalName}:
342 The gen_statem is globally registered in global.
343
344 {via,RegMod,ViaName}:
345 The gen_statem is registered in an alternative process reg‐
346 istry. The registry callback module RegMod is to export
347 functions register_name/2, unregister_name/1,
348 whereis_name/1, and send/2, which are to behave like the
349 corresponding functions in global. Thus, {via,global,Global‐
350 Name} is the same as {global,GlobalName}.
351
352 start_opt() =
353 {timeout, Time :: timeout()} |
354 {spawn_opt, [proc_lib:spawn_option()]} |
355 enter_loop_opt()
356
357 Options that can be used when starting a gen_statem server
358 through, for example, start_link/3.
359
360 start_ret() = {ok, pid()} | ignore | {error, term()}
361
362 Return value from the start functions, for example,
363 start_link/3.
364
365 enter_loop_opt() =
366 {hibernate_after, HibernateAfterTimeout :: timeout()} |
367 {debug, Dbgs :: [sys:debug_option()]}
368
369 Options that can be used when starting a gen_statem server
370 through, enter_loop/4-6.
371
372 hibernate_after:
373 HibernateAfterTimeout specifies that the gen_statem process
374 awaits any message for HibernateAfterTimeout milliseconds
375 and if no message is received, the process goes into hiber‐
376 nation automatically (by calling proc_lib:hibernate/3).
377
378 debug:
379 For every entry in Dbgs, the corresponding function in sys
380 is called.
381
382 from() = {To :: pid(), Tag :: term()}
383
384 Destination to use when replying through, for example, the
385 action() {reply,From,Reply} to a process that has called the
386 gen_statem server using call/2.
387
388 state() = state_name() | term()
389
390 If the callback mode is handle_event_function, the state can be
391 any term. After a state change (NextState =/= State), all post‐
392 poned events are retried.
393
394 state_name() = atom()
395
396 If the callback mode is state_functions, the state must be of
397 this type. After a state change (NextState =/= State), all post‐
398 poned events are retried.
399
400 data() = term()
401
402 A term in which the state machine implementation is to store any
403 server data it needs. The difference between this and the
404 state() itself is that a change in this data does not cause
405 postponed events to be retried. Hence, if a change in this data
406 would change the set of events that are handled, then that data
407 item is to be made a part of the state.
408
409 event_type() =
410 external_event_type() | timeout_event_type() | internal
411
412 There are 3 categories of events: external, timeout, and inter‐
413 nal.
414
415 internal events can only be generated by the state machine
416 itself through the transition action next_event.
417
418 external_event_type() = {call, From :: from()} | cast | info
419
420 External events are of 3 types: {call,From}, cast, or info.
421 Calls (synchronous) and casts originate from the corresponding
422 API functions. For calls, the event contains whom to reply to.
423 Type info originates from regular process messages sent to the
424 gen_statem.
425
426 timeout_event_type() =
427 timeout | {timeout, Name :: term()} | state_timeout
428
429 There are 3 types of time-out events that the state machine can
430 generate for itself with the corresponding timeout_action()s.
431
432 callback_mode_result() =
433 callback_mode() | [callback_mode() | state_enter()]
434
435 This is the return type from Module:callback_mode/0 and selects
436 callback mode and whether to do state enter calls, or not.
437
438 callback_mode() = state_functions | handle_event_function
439
440 The callback mode is selected when starting the gen_statem and
441 after code change using the return value from Module:call‐
442 back_mode/0.
443
444 state_functions:
445 The state must be of type state_name() and one callback
446 function per state, that is, Module:StateName/3, is used.
447
448 handle_event_function:
449 The state can be any term and the callback function Mod‐
450 ule:handle_event/4 is used for all states.
451
452 state_enter() = state_enter
453
454 Whether the state machine should use state enter calls or not is
455 selected when starting the gen_statem and after code change
456 using the return value from Module:callback_mode/0.
457
458 If Module:callback_mode/0 returns a list containing state_enter,
459 the gen_statem engine will, at every state change, call the
460 state callback with arguments (enter, OldState, Data) or (enter,
461 OldState, State, Data), depending on the callback mode. This may
462 look like an event but is really a call performed after the pre‐
463 vious state callback returned and before any event is delivered
464 to the new state callback. See Module:StateName/3 and Mod‐
465 ule:handle_event/4. Such a call can be repeated by returning a
466 repeat_state or repeat_state_and_data tuple from the state call‐
467 back.
468
469 If Module:callback_mode/0 does not return such a list, no state
470 enter calls are done.
471
472 If Module:code_change/4 should transform the state, it is
473 regarded as a state rename and not a state change, which will
474 not cause a state enter call.
475
476 Note that a state enter call will be done right before entering
477 the initial state even though this actually is not a state
478 change. In this case OldState =:= State, which cannot happen for
479 a subsequent state change, but will happen when repeating the
480 state enter call.
481
482 transition_option() =
483 postpone() |
484 hibernate() |
485 event_timeout() |
486 generic_timeout() |
487 state_timeout()
488
489 Transition options can be set by actions and modify the state
490 transition. The state transition takes place when the state
491 callback has processed an event and returns. Here are the
492 sequence of steps for a state transition:
493
494 * All returned actions are processed in order of appearance.
495 In this step all replies generated by any reply_action() are
496 sent. Other actions set transition_option()s that come into
497 play in subsequent steps.
498
499 * If state enter calls are used, and either it is the initial
500 state or one of the callback results repeat_state_and_data
501 or repeat_state_and_data is used the gen_statem engine calls
502 the current state callback with arguments (enter, State,
503 Data) or (enter, State, State, Data) (depending on callback
504 mode) and when it returns starts again from the top of this
505 sequence.
506
507 If state enter calls are used, and the state changes the
508 gen_statem engine calls the new state callback with argu‐
509 ments (enter, OldState, Data) or (enter, OldState, State,
510 Data) (depending on callback mode) and when it returns
511 starts again from the top of this sequence.
512
513 * If postpone() is true, the current event is postponed.
514
515 * If this is a state change, the queue of incoming events is
516 reset to start with the oldest postponed.
517
518 * All events stored with action() next_event are inserted to
519 be processed before previously queued events.
520
521 * Time-out timers event_timeout(), generic_timeout() and
522 state_timeout() are handled. Time-outs with zero time are
523 guaranteed to be delivered to the state machine before any
524 external not yet received event so if there is such a time-
525 out requested, the corresponding time-out zero event is
526 enqueued as the newest received event; that is after already
527 queued events such as inserted and postponed events.
528
529 Any event cancels an event_timeout() so a zero time event
530 time-out is only generated if the event queue is empty.
531
532 A state change cancels a state_timeout() and any new transi‐
533 tion option of this type belongs to the new state, that is;
534 a state_timeout() applies to the state the state machine
535 enters.
536
537 * If there are enqueued events the state callback for the pos‐
538 sibly new state is called with the oldest enqueued event,
539 and we start again from the top of this sequence.
540
541 * Otherwise the gen_statem goes into receive or hibernation
542 (if hibernate() is true) to wait for the next message. In
543 hibernation the next non-system event awakens the
544 gen_statem, or rather the next incoming message awakens the
545 gen_statem, but if it is a system event it goes right back
546 into hibernation. When a new message arrives the state call‐
547 back is called with the corresponding event, and we start
548 again from the top of this sequence.
549
550 postpone() = boolean()
551
552 If true, postpones the current event and retries it after a
553 state change (NextState =/= State).
554
555 hibernate() = boolean()
556
557 If true, hibernates the gen_statem by calling proc_lib:hiber‐
558 nate/3 before going into receive to wait for a new external
559 event.
560
561 Note:
562 If there are enqueued events to process when hibrnation is
563 requested, this is optimized by not hibernating but instead
564 calling erlang:garbage_collect/0 to simulate that the gen_statem
565 entered hibernation and immediately got awakened by an enqueued
566 event.
567
568
569 event_timeout() = timeout() | integer()
570
571 Starts a timer set by enter_action() timeout. When the timer
572 expires an event of event_type() timeout will be generated. See
573 erlang:start_timer/4 for how Time and Options are interpreted.
574 Future erlang:start_timer/4 Options will not necessarily be sup‐
575 ported.
576
577 Any event that arrives cancels this time-out. Note that a
578 retried or inserted event counts as arrived. So does a state
579 time-out zero event, if it was generated before this time-out is
580 requested.
581
582 If Time is infinity, no timer is started, as it never would
583 expire anyway.
584
585 If Time is relative and 0 no timer is actually started, instead
586 the the time-out event is enqueued to ensure that it gets pro‐
587 cessed before any not yet received external event, but after
588 already queued events.
589
590 Note that it is not possible nor needed to cancel this time-out,
591 as it is cancelled automatically by any other event.
592
593 generic_timeout() = timeout() | integer()
594
595 Starts a timer set by enter_action() {timeout,Name}. When the
596 timer expires an event of event_type() {timeout,Name} will be
597 generated. See erlang:start_timer/4 for how Time and Options are
598 interpreted. Future erlang:start_timer/4 Options will not neces‐
599 sarily be supported.
600
601 If Time is infinity, no timer is started, as it never would
602 expire anyway.
603
604 If Time is relative and 0 no timer is actually started, instead
605 the the time-out event is enqueued to ensure that it gets pro‐
606 cessed before any not yet received external event.
607
608 Setting a timer with the same Name while it is running will
609 restart it with the new time-out value. Therefore it is possible
610 to cancel a specific time-out by setting it to infinity.
611
612 state_timeout() = timeout() | integer()
613
614 Starts a timer set by enter_action() state_timeout. When the
615 timer expires an event of event_type() state_timeout will be
616 generated. See erlang:start_timer/4 for how Time and Options are
617 interpreted. Future erlang:start_timer/4 Options will not neces‐
618 sarily be supported.
619
620 If Time is infinity, no timer is started, as it never would
621 expire anyway.
622
623 If Time is relative and 0 no timer is actually started, instead
624 the the time-out event is enqueued to ensure that it gets pro‐
625 cessed before any not yet received external event.
626
627 Setting this timer while it is running will restart it with the
628 new time-out value. Therefore it is possible to cancel this
629 time-out by setting it to infinity.
630
631 timeout_option() = {abs, Abs :: boolean()}
632
633 If Abs is true an absolute timer is started, and if it is false
634 a relative, which is the default. See erlang:start_timer/4 for
635 details.
636
637 action() =
638 postpone |
639 {postpone, Postpone :: postpone()} |
640 {next_event,
641 EventType :: event_type(),
642 EventContent :: term()} |
643 enter_action()
644
645 These transition actions can be invoked by returning them from
646 the state callback when it is called with an event, from Mod‐
647 ule:init/1 or by giving them to enter_loop/5,6.
648
649 Actions are executed in the containing list order.
650
651 Actions that set transition options override any previous of
652 the same type, so the last in the containing list wins. For
653 example, the last postpone() overrides any previous postpone()
654 in the list.
655
656 postpone:
657 Sets the transition_option() postpone() for this state tran‐
658 sition. This action is ignored when returned from Mod‐
659 ule:init/1 or given to enter_loop/5,6, as there is no event
660 to postpone in those cases.
661
662 next_event:
663 This action does not set any transition_option() but instead
664 stores the specified EventType and EventContent for inser‐
665 tion after all actions have been executed.
666
667 The stored events are inserted in the queue as the next to
668 process before any already queued events. The order of these
669 stored events is preserved, so the first next_event in the
670 containing list becomes the first to process.
671
672 An event of type internal is to be used when you want to
673 reliably distinguish an event inserted this way from any
674 external event.
675
676 enter_action() =
677 hibernate |
678 {hibernate, Hibernate :: hibernate()} |
679 timeout_action() |
680 reply_action()
681
682 These transition actions can be invoked by returning them from
683 the state callback, from Module:init/1 or by giving them to
684 enter_loop/5,6.
685
686 Actions are executed in the containing list order.
687
688 Actions that set transition options override any previous of the
689 same type, so the last in the containing list wins. For example,
690 the last event_timeout() overrides any previous event_timeout()
691 in the list.
692
693 hibernate:
694 Sets the transition_option() hibernate() for this state
695 transition.
696
697 timeout_action() =
698 (Time :: event_timeout()) |
699 {timeout, Time :: event_timeout(), EventContent :: term()} |
700 {timeout,
701 Time :: event_timeout(),
702 EventContent :: term(),
703 Options :: timeout_option() | [timeout_option()]} |
704 {{timeout, Name :: term()},
705 Time :: generic_timeout(),
706 EventContent :: term()} |
707 {{timeout, Name :: term()},
708 Time :: generic_timeout(),
709 EventContent :: term(),
710 Options :: timeout_option() | [timeout_option()]} |
711 {state_timeout,
712 Time :: state_timeout(),
713 EventContent :: term()} |
714 {state_timeout,
715 Time :: state_timeout(),
716 EventContent :: term(),
717 Options :: timeout_option() | [timeout_option()]} |
718 timeout_cancel_action() |
719 timeout_update_action()
720
721 These transition actions can be invoked by returning them from
722 the state callback, from Module:init/1 or by giving them to
723 enter_loop/5,6.
724
725 These time-out actions sets time-out transition options.
726
727 Time:
728 Short for {timeout,Time,Time}, that is, the time-out message
729 is the time-out time. This form exists to make the state
730 callback return value {next_state,NextState,NewData,Time}
731 allowed like for gen_fsm.
732
733 timeout:
734 Sets the transition_option() event_timeout() to Time with
735 EventContent and time-out options Options.
736
737 {timeout,Name}:
738 Sets the transition_option() generic_timeout() to Time for
739 Name with EventContent and time-out options Options.
740
741 state_timeout:
742 Sets the transition_option() state_timeout() to Time with
743 EventContent and time-out options Options.
744
745 timeout_cancel_action() =
746 {timeout, cancel} |
747 {{timeout, Name :: term()}, cancel} |
748 {state_timeout, cancel}
749
750 This is a shorter and clearer form of timeout_action() with
751 Time = infinity which cancels a time-out.
752
753 timeout_update_action() =
754 {timeout, update, EventContent :: term()} |
755 {{timeout, Name :: term()}, update, EventContent :: term()} |
756 {state_timeout, update, EventContent :: term()}
757
758 Updates a time-out with a new EventContent. See time‐
759 out_action() for how to start a time-out.
760
761 If no time-out of the same type is active instead insert the
762 time-out event just like when starting a time-out with relative
763 Time = 0.
764
765 reply_action() = {reply, From :: from(), Reply :: term()}
766
767 This transition action can be invoked by returning it from the
768 state callback, from Module:init/1 or by giving it to
769 enter_loop/5,6.
770
771 It does not set any transition_option() but instead replies to a
772 caller waiting for a reply in call/2. From must be the term from
773 argument {call,From} in a call to a state callback.
774
775 Note that using this action from Module:init/1 or enter_loop/5,6
776 would be weird on the border of witchcraft since there has been
777 no earlier call to a state callback in this server.
778
779 init_result(StateType) =
780 {ok, State :: StateType, Data :: data()} |
781 {ok,
782 State :: StateType,
783 Data :: data(),
784 Actions :: [action()] | action()} |
785 ignore |
786 {stop, Reason :: term()}
787
788 For a succesful initialization, State is the initial state() and
789 Data the initial server data() of the gen_statem.
790
791 The Actions are executed when entering the first state just as
792 for a state callback, except that the action postpone is forced
793 to false since there is no event to postpone.
794
795 For an unsuccesful initialization, {stop,Reason} or ignore
796 should be used; see start_link/3,4.
797
798 state_enter_result(State) =
799 {next_state, State, NewData :: data()} |
800 {next_state, State,
801 NewData :: data(),
802 Actions :: [enter_action()] | enter_action()} |
803 state_callback_result(enter_action())
804
805 State is the current state and it cannot be changed since the
806 state callback was called with a state enter call.
807
808 next_state:
809 The gen_statem does a state transition to State, which has
810 to be the current state, sets NewData, and executes all
811 Actions.
812
813 event_handler_result(StateType) =
814 {next_state, NextState :: StateType, NewData :: data()} |
815 {next_state,
816 NextState :: StateType,
817 NewData :: data(),
818 Actions :: [action()] | action()} |
819 state_callback_result(action())
820
821 StateType is state_name() if callback mode is state_functions,
822 or state() if callback mode is handle_event_function.
823
824 next_state:
825 The gen_statem does a state transition to NextState (which
826 can be the same as the current state), sets NewData, and
827 executes all Actions. If NextState =/= CurrentState the
828 state transition is a state change.
829
830 state_callback_result(ActionType) =
831 {keep_state, NewData :: data()} |
832 {keep_state,
833 NewData :: data(),
834 Actions :: [ActionType] | ActionType} |
835 keep_state_and_data |
836 {keep_state_and_data, Actions :: [ActionType] | ActionType} |
837 {repeat_state, NewData :: data()} |
838 {repeat_state,
839 NewData :: data(),
840 Actions :: [ActionType] | ActionType} |
841 repeat_state_and_data |
842 {repeat_state_and_data, Actions :: [ActionType] | ActionType} |
843 stop |
844 {stop, Reason :: term()} |
845 {stop, Reason :: term(), NewData :: data()} |
846 {stop_and_reply,
847 Reason :: term(),
848 Replies :: [reply_action()] | reply_action()} |
849 {stop_and_reply,
850 Reason :: term(),
851 Replies :: [reply_action()] | reply_action(),
852 NewData :: data()}
853
854 ActionType is enter_action() if the state callback was called
855 with a state enter call and action() if the state callback was
856 called with an event.
857
858 keep_state:
859 The same as {next_state,CurrentState,NewData,Actions}.
860
861 keep_state_and_data:
862 The same as {keep_state,CurrentData,Actions}.
863
864 repeat_state:
865 If the gen_statem runs with state enter calls, the state
866 enter call is repeated, see type transition_option(), other
867 than that repeat_state is the same as keep_state.
868
869 repeat_state_and_data:
870 The same as {repeat_state,CurrentData,Actions}.
871
872 stop:
873 Terminates the gen_statem by calling Module:terminate/3 with
874 Reason and NewData, if specified.
875
876 stop_and_reply:
877 Sends all Replies, then terminates the gen_statem by calling
878 Module:terminate/3 with Reason and NewData, if specified.
879
880 All these terms are tuples or atoms and this property will hold
881 in any future version of gen_statem.
882
884 call(ServerRef :: server_ref(), Request :: term()) ->
885 Reply :: term()
886
887 call(ServerRef :: server_ref(),
888 Request :: term(),
889 Timeout ::
890 timeout() |
891 {clean_timeout, T :: timeout()} |
892 {dirty_timeout, T :: timeout()}) ->
893 Reply :: term()
894
895 Makes a synchronous call to the gen_statem ServerRef by sending
896 a request and waiting until its reply arrives. The gen_statem
897 calls the state callback with event_type() {call,From} and event
898 content Request.
899
900 A Reply is generated when a state callback returns with
901 {reply,From,Reply} as one action(), and that Reply becomes the
902 return value of this function.
903
904 Timeout is an integer > 0, which specifies how many milliseconds
905 to wait for a reply, or the atom infinity to wait indefinitely,
906 which is the default. If no reply is received within the speci‐
907 fied time, the function call fails.
908
909 Note:
910 For Timeout < infinity, to avoid getting a late reply in the
911 caller's inbox if the caller should catch exceptions, this func‐
912 tion spawns a proxy process that does the call. A late reply
913 gets delivered to the dead proxy process, hence gets discarded.
914 This is less efficient than using Timeout == infinity.
915
916
917 Timeout can also be a tuple {clean_timeout,T} or {dirty_time‐
918 out,T}, where T is the time-out time. {clean_timeout,T} works
919 like just T described in the note above and uses a proxy process
920 while {dirty_timeout,T} bypasses the proxy process which is more
921 lightweight.
922
923 Note:
924 If you combine catching exceptions from this function with
925 {dirty_timeout,T} to avoid that the calling process dies when
926 the call times out, you will have to be prepared to handle a
927 late reply. Note that there is an odd chance to get a late reply
928 even with {dirty_timeout,infinity} or infinity for example in
929 the event of network problems. So why not just let the calling
930 process die by not catching the exception?
931
932
933 The call can also fail, for example, if the gen_statem dies
934 before or during this function call.
935
936 cast(ServerRef :: server_ref(), Msg :: term()) -> ok
937
938 Sends an asynchronous event to the gen_statem ServerRef and
939 returns ok immediately, ignoring if the destination node or
940 gen_statem does not exist. The gen_statem calls the state call‐
941 back with event_type() cast and event content Msg.
942
943 enter_loop(Module :: module(),
944 Opts :: [enter_loop_opt()],
945 State :: state(),
946 Data :: data()) ->
947 no_return()
948
949 The same as enter_loop/6 with Actions = [] except that no
950 server_name() must have been registered. This creates an anony‐
951 mous server.
952
953 enter_loop(Module :: module(),
954 Opts :: [enter_loop_opt()],
955 State :: state(),
956 Data :: data(),
957 Server_or_Actions :: server_name() | pid() | [action()]) ->
958 no_return()
959
960 If Server_or_Actions is a list(), the same as enter_loop/6
961 except that no server_name() must have been registered and
962 Actions = Server_or_Actions. This creates an anonymous server.
963
964 Otherwise the same as enter_loop/6 with Server =
965 Server_or_Actions and Actions = [].
966
967 enter_loop(Module :: module(),
968 Opts :: [enter_loop_opt()],
969 State :: state(),
970 Data :: data(),
971 Server :: server_name() | pid(),
972 Actions :: [action()] | action()) ->
973 no_return()
974
975 Makes the calling process become a gen_statem. Does not return,
976 instead the calling process enters the gen_statem receive loop
977 and becomes a gen_statem server. The process must have been
978 started using one of the start functions in proc_lib. The user
979 is responsible for any initialization of the process, including
980 registering a name for it.
981
982 This function is useful when a more complex initialization pro‐
983 cedure is needed than the gen_statem behavior provides.
984
985 Module, Opts have the same meaning as when calling
986 start[_link]/3,4.
987
988 If Server is self() an anonymous server is created just as when
989 using start[_link]/3. If Server is a server_name() a named
990 server is created just as when using start[_link]/4. However,
991 the server_name() name must have been registered accordingly
992 before this function is called.
993
994 State, Data, and Actions have the same meanings as in the return
995 value of Module:init/1. Also, the callback module does not need
996 to export a Module:init/1 function.
997
998 The function fails if the calling process was not started by a
999 proc_lib start function, or if it is not registered according to
1000 server_name().
1001
1002 reply(Replies :: [reply_action()] | reply_action()) -> ok
1003
1004 reply(From :: from(), Reply :: term()) -> ok
1005
1006 This function can be used by a gen_statem to explicitly send a
1007 reply to a process that waits in call/2 when the reply cannot be
1008 defined in the return value of a state callback.
1009
1010 From must be the term from argument {call,From} to the state
1011 callback. A reply or multiple replies canalso be sent using one
1012 or several reply_action()s from a state callback.
1013
1014 Note:
1015 A reply sent with this function is not visible in sys debug out‐
1016 put.
1017
1018
1019 start(Module :: module(), Args :: term(), Opts :: [start_opt()]) ->
1020 start_ret()
1021
1022 start(ServerName :: server_name(),
1023 Module :: module(),
1024 Args :: term(),
1025 Opts :: [start_opt()]) ->
1026 start_ret()
1027
1028 Creates a standalone gen_statem process according to OTP design
1029 principles (using proc_lib primitives). As it does not get
1030 linked to the calling process, this start function cannot be
1031 used by a supervisor to start a child.
1032
1033 For a description of arguments and return values, see
1034 start_link/3,4.
1035
1036 start_link(Module :: module(),
1037 Args :: term(),
1038 Opts :: [start_opt()]) ->
1039 start_ret()
1040
1041 start_link(ServerName :: server_name(),
1042 Module :: module(),
1043 Args :: term(),
1044 Opts :: [start_opt()]) ->
1045 start_ret()
1046
1047 Creates a gen_statem process according to OTP design principles
1048 (using proc_lib primitives) that is linked to the calling
1049 process. This is essential when the gen_statem must be part of a
1050 supervision tree so it gets linked to its supervisor.
1051
1052 The gen_statem process calls Module:init/1 to initialize the
1053 server. To ensure a synchronized startup procedure,
1054 start_link/3,4 does not return until Module:init/1 has returned.
1055
1056 ServerName specifies the server_name() to register for the
1057 gen_statem. If the gen_statem is started with start_link/3, no
1058 ServerName is provided and the gen_statem is not registered.
1059
1060 Module is the name of the callback module.
1061
1062 Args is an arbitrary term that is passed as the argument to Mod‐
1063 ule:init/1.
1064
1065 * If option {timeout,Time} is present in Opts, the gen_statem
1066 is allowed to spend Time milliseconds initializing or it
1067 terminates and the start function returns {error,timeout}.
1068
1069 * If option {hibernate_after,HibernateAfterTimeout} is
1070 present, the gen_statem process awaits any message for
1071 HibernateAfterTimeout milliseconds and if no message is
1072 received, the process goes into hibernation automatically
1073 (by calling proc_lib:hibernate/3).
1074
1075 * If option {debug,Dbgs} is present in Opts, debugging through
1076 sys is activated.
1077
1078 * If option {spawn_opt,SpawnOpts} is present in Opts,
1079 SpawnOpts is passed as option list to erlang:spawn_opt/2,
1080 which is used to spawn the gen_statem process.
1081
1082 Note:
1083 Using spawn option monitor is not allowed, it causes this func‐
1084 tion to fail with reason badarg.
1085
1086
1087 If the gen_statem is successfully created and initialized, this
1088 function returns {ok,Pid}, where Pid is the pid() of the
1089 gen_statem. If a process with the specified ServerName exists
1090 already, this function returns {error,{already_started,Pid}},
1091 where Pid is the pid() of that process.
1092
1093 If Module:init/1 fails with Reason, this function returns
1094 {error,Reason}. If Module:init/1 returns {stop,Reason} or
1095 ignore, the process is terminated and this function returns
1096 {error,Reason} or ignore, respectively.
1097
1098 stop(ServerRef :: server_ref()) -> ok
1099
1100 The same as stop(ServerRef, normal, infinity).
1101
1102 stop(ServerRef :: server_ref(),
1103 Reason :: term(),
1104 Timeout :: timeout()) ->
1105 ok
1106
1107 Orders the gen_statem ServerRef to exit with the specified Rea‐
1108 son and waits for it to terminate. The gen_statem calls Mod‐
1109 ule:terminate/3 before exiting.
1110
1111 This function returns ok if the server terminates with the
1112 expected reason. Any other reason than normal, shutdown, or
1113 {shutdown,Term} causes an error report to be issued through log‐
1114 ger(3). The default Reason is normal.
1115
1116 Timeout is an integer > 0, which specifies how many milliseconds
1117 to wait for the server to terminate, or the atom infinity to
1118 wait indefinitely. Defaults to infinity. If the server does not
1119 terminate within the specified time, a timeout exception is
1120 raised.
1121
1122 If the process does not exist, a noproc exception is raised.
1123
1125 The following functions are to be exported from a gen_statem callback
1126 module.
1127
1129 Module:callback_mode() -> CallbackMode
1130
1131 Types:
1132
1133 CallbackMode = callback_mode() | [ callback_mode() |
1134 state_enter() ]
1135
1136 This function is called by a gen_statem when it needs to find
1137 out the callback mode of the callback module. The value is
1138 cached by gen_statem for efficiency reasons, so this function is
1139 only called once after server start and after code change, but
1140 before the first state callback in the current code version is
1141 called. More occasions may be added in future versions of
1142 gen_statem.
1143
1144 Server start happens either when Module:init/1 returns or when
1145 enter_loop/4-6 is called. Code change happens when Mod‐
1146 ule:code_change/4 returns.
1147
1148 The CallbackMode is either just callback_mode() or a list con‐
1149 taining callback_mode() and possibly the atom state_enter.
1150
1151 Note:
1152 If this function's body does not return an inline constant value
1153 the callback module is doing something strange.
1154
1155
1156 Module:code_change(OldVsn, OldState, OldData, Extra) -> Result
1157
1158 Types:
1159
1160 OldVsn = Vsn | {down,Vsn}
1161 Vsn = term()
1162 OldState = NewState = term()
1163 Extra = term()
1164 Result = {ok,NewState,NewData} | Reason
1165 OldState = NewState = state()
1166 OldData = NewData = data()
1167 Reason = term()
1168
1169 Note:
1170 This callback is optional, so callback modules need not export
1171 it. If a release upgrade/downgrade with Change =
1172 {advanced,Extra} specified in the .appup file is made when
1173 code_change/4 is not implemented the process will crash with
1174 exit reason undef.
1175
1176
1177 This function is called by a gen_statem when it is to update its
1178 internal state during a release upgrade/downgrade, that is, when
1179 the instruction {update,Module,Change,...}, where Change =
1180 {advanced,Extra}, is specified in the appup file. For more
1181 information, see OTP Design Principles.
1182
1183 For an upgrade, OldVsn is Vsn, and for a downgrade, OldVsn is
1184 {down,Vsn}. Vsn is defined by the vsn attribute(s) of the old
1185 version of the callback module Module. If no such attribute is
1186 defined, the version is the checksum of the Beam file.
1187
1188 OldState and OldData is the internal state of the gen_statem.
1189
1190 Extra is passed "as is" from the {advanced,Extra} part of the
1191 update instruction.
1192
1193 If successful, the function must return the updated internal
1194 state in an {ok,NewState,NewData} tuple.
1195
1196 If the function returns a failure Reason, the ongoing upgrade
1197 fails and rolls back to the old release. Note that Reason cannot
1198 be an {ok,_,_} tuple since that will be regarded as a {ok,New‐
1199 State,NewData} tuple, and that a tuple matching {ok,_} is an
1200 also invalid failure Reason. It is recommended to use an atom as
1201 Reason since it will be wrapped in an {error,Reason} tuple.
1202
1203 Also note when upgrading a gen_statem, this function and hence
1204 the Change = {advanced,Extra} parameter in the appup file is not
1205 only needed to update the internal state or to act on the Extra
1206 argument. It is also needed if an upgrade or downgrade should
1207 change callback mode, or else the callback mode after the code
1208 change will not be honoured, most probably causing a server
1209 crash.
1210
1211 Module:init(Args) -> Result(StateType)
1212
1213 Types:
1214
1215 Args = term()
1216 Result(StateType) = init_result(StateType)
1217
1218 Whenever a gen_statem is started using start_link/3,4 or
1219 start/3,4, this function is called by the new process to ini‐
1220 tialize the implementation state and server data.
1221
1222 Args is the Args argument provided to that start function.
1223
1224 Note:
1225 Note that if the gen_statem is started through proc_lib and
1226 enter_loop/4-6, this callback will never be called. Since this
1227 callback is not optional it can in that case be implemented as:
1228
1229 init(Args) -> erlang:error(not_implemented, [Args]).
1230
1231
1232 Module:format_status(Opt, [PDict,State,Data]) -> Status
1233
1234 Types:
1235
1236 Opt = normal | terminate
1237 PDict = [{Key, Value}]
1238 State = state()
1239 Data = data()
1240 Key = term()
1241 Value = term()
1242 Status = term()
1243
1244 Note:
1245 This callback is optional, so a callback module does not need to
1246 export it. The gen_statem module provides a default implementa‐
1247 tion of this function that returns {State,Data}.
1248
1249 If this callback is exported but fails, to hide possibly sensi‐
1250 tive data, the default function will instead return
1251 {State,Info}, where Info says nothing but the fact that for‐
1252 mat_status/2 has crashed.
1253
1254
1255 This function is called by a gen_statem process when any of the
1256 following apply:
1257
1258 *
1259 One of sys:get_status/1,2 is invoked to get the gen_statem
1260 status. Opt is set to the atom normal for this case.
1261
1262 *
1263 The gen_statem terminates abnormally and logs an error. Opt
1264 is set to the atom terminate for this case.
1265
1266 This function is useful for changing the form and appearance of
1267 the gen_statem status for these cases. A callback module wishing
1268 to change the sys:get_status/1,2 return value and how its status
1269 appears in termination error logs exports an instance of for‐
1270 mat_status/2, which returns a term describing the current status
1271 of the gen_statem.
1272
1273 PDict is the current value of the process dictionary of the
1274 gen_statem.
1275
1276 State is the internal state of the gen_statem.
1277
1278 Data is the internal server data of the gen_statem.
1279
1280 The function is to return Status, a term that contains the
1281 appropriate details of the current state and status of the
1282 gen_statem. There are no restrictions on the form Status can
1283 take, but for the sys:get_status/1,2 case (when Opt is normal),
1284 the recommended form for the Status value is [{data, [{"State",
1285 Term}]}], where Term provides relevant details of the gen_statem
1286 state. Following this recommendation is not required, but it
1287 makes the callback module status consistent with the rest of the
1288 sys:get_status/1,2 return value.
1289
1290 One use for this function is to return compact alternative state
1291 representations to avoid having large state terms printed in log
1292 files. Another use is to hide sensitive data from being written
1293 to the error log.
1294
1295 Module:StateName(enter, OldState, Data) -> StateEnterResult(StateName)
1296 Module:StateName(EventType, EventContent, Data) -> StateFunctionResult
1297 Module:handle_event(enter, OldState, State, Data) -> StateEnterRe‐
1298 sult(State)
1299 Module:handle_event(EventType, EventContent, State, Data) -> Han‐
1300 dleEventResult
1301
1302 Types:
1303
1304 EventType = event_type()
1305 EventContent = term()
1306 State = state()
1307 Data = NewData = data()
1308 StateEnterResult(StateName) = state_enter_result(StateName)
1309 StateFunctionResult = event_handler_result(state_name())
1310 StateEnterResult(State) = state_enter_result(State)
1311 HandleEventResult = event_handler_result(state())
1312
1313 Whenever a gen_statem receives an event from call/2, cast/2, or
1314 as a normal process message, one of these functions is called.
1315 If callback mode is state_functions, Module:StateName/3 is
1316 called, and if it is handle_event_function, Module:han‐
1317 dle_event/4 is called.
1318
1319 If EventType is {call,From}, the caller waits for a reply. The
1320 reply can be sent from this or from any other state callback by
1321 returning with {reply,From,Reply} in Actions, in Replies, or by
1322 calling reply(From, Reply).
1323
1324 If this function returns with a next state that does not match
1325 equal (=/=) to the current state, all postponed events are
1326 retried in the next state.
1327
1328 The only difference between StateFunctionResult and HandleEven‐
1329 tResult is that for StateFunctionResult the next state must be
1330 an atom, but for HandleEventResult there is no restriction on
1331 the next state.
1332
1333 For options that can be set and actions that can be done by
1334 gen_statem after returning from this function, see action().
1335
1336 When the gen_statem runs with state enter calls, these functions
1337 are also called with arguments (enter, OldState, ...) during
1338 every state change. In this case there are some restrictions on
1339 the actions that may be returned: postpone() is not allowed
1340 since a state enter call is not an event so there is no event to
1341 postpone, and {next_event,_,_} is not allowed since using state
1342 enter calls should not affect how events are consumed and pro‐
1343 duced. You may also not change states from this call. Should you
1344 return {next_state,NextState, ...} with NextState =/= State the
1345 gen_statem crashes. Note that it is actually allowed to use
1346 {repeat_state, NewData, ...} although it makes little sense
1347 since you immediately will be called again with a new state
1348 enter call making this just a weird way of looping, and there
1349 are better ways to loop in Erlang. If you do not update NewData
1350 and have some loop termination condition, or if you use
1351 {repeat_state_and_data, _} or repeat_state_and_data you have an
1352 infinite loop! You are advised to use {keep_state,...},
1353 {keep_state_and_data,_} or keep_state_and_data since changing
1354 states from a state enter call is not possible anyway.
1355
1356 Note the fact that you can use throw to return the result, which
1357 can be useful. For example to bail out with
1358 throw(keep_state_and_data) from deep within complex code that
1359 cannot return {next_state,State,Data} because State or Data is
1360 no longer in scope.
1361
1362 Module:terminate(Reason, State, Data) -> Ignored
1363
1364 Types:
1365
1366 Reason = normal | shutdown | {shutdown,term()} | term()
1367 State = state()
1368 Data = data()
1369 Ignored = term()
1370
1371 Note:
1372 This callback is optional, so callback modules need not export
1373 it. The gen_statem module provides a default implementation
1374 without cleanup.
1375
1376
1377 This function is called by a gen_statem when it is about to ter‐
1378 minate. It is to be the opposite of Module:init/1 and do any
1379 necessary cleaning up. When it returns, the gen_statem termi‐
1380 nates with Reason. The return value is ignored.
1381
1382 Reason is a term denoting the stop reason and State is the
1383 internal state of the gen_statem.
1384
1385 Reason depends on why the gen_statem is terminating. If it is
1386 because another callback function has returned, a stop tuple
1387 {stop,Reason} in Actions, Reason has the value specified in that
1388 tuple. If it is because of a failure, Reason is the error rea‐
1389 son.
1390
1391 If the gen_statem is part of a supervision tree and is ordered
1392 by its supervisor to terminate, this function is called with
1393 Reason = shutdown if both the following conditions apply:
1394
1395 * The gen_statem has been set to trap exit signals.
1396
1397 * The shutdown strategy as defined in the supervisor's child
1398 specification is an integer time-out value, not brutal_kill.
1399
1400 Even if the gen_statem is not part of a supervision tree, this
1401 function is called if it receives an 'EXIT' message from its
1402 parent. Reason is the same as in the 'EXIT' message.
1403
1404 Otherwise, the gen_statem is immediately terminated.
1405
1406 Notice that for any other reason than normal, shutdown, or
1407 {shutdown,Term}, the gen_statem is assumed to terminate because
1408 of an error and an error report is issued using logger(3).
1409
1411 gen_event(3), gen_fsm(3), gen_server(3), proc_lib(3), supervisor(3),
1412 sys(3).
1413
1414
1415
1416Ericsson AB stdlib 3.10 gen_statem(3)