1gen_event(3) Erlang Module Definition gen_event(3)
2
3
4
6 gen_event - Generic event handling behavior.
7
9 This behavior module provides event handling functionality. It consists
10 of a generic event manager process with any number of event handlers
11 that are added and deleted dynamically.
12
13 An event manager implemented using this module has a standard set of
14 interface functions and includes functionality for tracing and error
15 reporting. It also fits into an OTP supervision tree. For more informa‐
16 tion, see OTP Design Principles.
17
18 Each event handler is implemented as a callback module exporting a pre‐
19 defined set of functions. The relationship between the behavior func‐
20 tions and the callback functions is as follows:
21
22 gen_event module Callback module
23 ---------------- ---------------
24 gen_event:start
25 gen_event:start_monitor
26 gen_event:start_link -----> -
27
28 gen_event:add_handler
29 gen_event:add_sup_handler -----> Module:init/1
30
31 gen_event:notify
32 gen_event:sync_notify -----> Module:handle_event/2
33
34 gen_event:send_request
35 gen_event:call -----> Module:handle_call/2
36
37 - -----> Module:handle_info/2
38
39 gen_event:delete_handler -----> Module:terminate/2
40
41 gen_event:swap_handler
42 gen_event:swap_sup_handler -----> Module1:terminate/2
43 Module2:init/1
44
45 gen_event:which_handlers -----> -
46
47 gen_event:stop -----> Module:terminate/2
48
49 - -----> Module:code_change/3
50
51 As each event handler is one callback module, an event manager has many
52 callback modules that are added and deleted dynamically. gen_event is
53 therefore more tolerant of callback module errors than the other behav‐
54 iors. If a callback function for an installed event handler fails with
55 Reason, or returns a bad value Term, the event manager does not fail.
56 It deletes the event handler by calling callback function Module:termi‐
57 nate/2, giving as argument {error,{'EXIT',Reason}} or {error,Term}, re‐
58 spectively. No other event handler is affected.
59
60 A gen_event process handles system messages as described in sys(3). The
61 sys module can be used for debugging an event manager.
62
63 Notice that an event manager does trap exit signals automatically.
64
65 The gen_event process can go into hibernation (see erlang:hibernate/3)
66 if a callback function in a handler module specifies hibernate in its
67 return value. This can be useful if the server is expected to be idle
68 for a long time. However, use this feature with care, as hibernation
69 implies at least two garbage collections (when hibernating and shortly
70 after waking up) and is not something you want to do between each event
71 handled by a busy event manager.
72
73 Notice that when multiple event handlers are invoked, it is sufficient
74 that one single event handler returns a hibernate request for the whole
75 event manager to go into hibernation.
76
77 Unless otherwise stated, all functions in this module fail if the spec‐
78 ified event manager does not exist or if bad arguments are specified.
79
80 Note:
81 For some important information about distributed signals, see the
82 Blocking Signaling Over Distribution section in the Processes chapter
83 of the Erlang Reference Manual . Blocking signaling can, for example,
84 cause call timeouts in gen_event to be significantly delayed.
85
86
88 handler() = atom() | {atom(), term()}
89
90 handler_args() = term()
91
92 add_handler_ret() = ok | term() | {'EXIT', term()}
93
94 del_handler_ret() = ok | term() | {'EXIT', term()}
95
96 emgr_ref() =
97 atom() |
98 {atom(), atom()} |
99 {global, term()} |
100 {via, atom(), term()} |
101 pid()
102
103 request_id()
104
105 An opaque request identifier. See send_request/3 for details.
106
107 request_id_collection()
108
109 An opaque collection of request identifiers (request_id()) where
110 each request identifier can be associated with a label chosen by
111 the user. For more information see reqids_new/0.
112
113 response_timeout() = timeout() | {abs, integer()}
114
115 Used to set a time limit on how long to wait for a response us‐
116 ing either receive_response/2, receive_response/3, wait_re‐
117 sponse/2, or wait_response/3. The time unit used is millisecond.
118 Currently valid values:
119
120 0..4294967295:
121 Timeout relative to current time in milliseconds.
122
123 infinity:
124 Infinite timeout. That is, the operation will never time
125 out.
126
127 {abs, Timeout}:
128 An absolute Erlang monotonic time timeout in milliseconds.
129 That is, the operation will time out when erlang:mono‐
130 tonic_time(millisecond) returns a value larger than or equal
131 to Timeout. Timeout is not allowed to identify a time fur‐
132 ther into the future than 4294967295 milliseconds. Identify‐
133 ing the timeout using an absolute timeout value is espe‐
134 cially handy when you have a deadline for responses corre‐
135 sponding to a complete collection of requests (re‐
136 quest_id_collection()) , since you do not have to recalcu‐
137 late the relative time until the deadline over and over
138 again.
139
140 format_status() =
141 #{state => term(),
142 message => term(),
143 reason => term(),
144 log => [sys:system_event()]}
145
146 A map that describes the gen_event process status. The keys are:
147
148 state:
149 The internal state of the event handler.
150
151 message:
152 The message that caused the event handler to terminate.
153
154 reason:
155 The reason that caused the event handler to terminate.
156
157 log:
158 The sys log of the server.
159
160 New associations may be added into the status map without prior
161 notice.
162
164 add_handler(EventMgrRef, Handler, Args) -> Result
165
166 Types:
167
168 EventMgrRef = Name | {Name,Node} | {global,GlobalName} |
169 {via,Module,ViaName} | pid()
170 Name = Node = atom()
171 GlobalName = ViaName = term()
172 Handler = Module | {Module,Id}
173 Module = atom()
174 Id = term()
175 Args = term()
176 Result = ok | {'EXIT',Reason} | term()
177 Reason = term()
178
179 Adds a new event handler to event manager EventMgrRef. The event
180 manager calls Module:init/1 to initiate the event handler and
181 its internal state.
182
183 EventMgrRef can be any of the following:
184
185 * The pid
186
187 * Name, if the event manager is locally registered
188
189 * {Name,Node}, if the event manager is locally registered at
190 another node
191
192 * {global,GlobalName}, if the event manager is globally regis‐
193 tered
194
195 * {via,Module,ViaName}, if the event manager is registered
196 through an alternative process registry
197
198 Handler is the name of the callback module Module or a tuple
199 {Module,Id}, where Id is any term. The {Module,Id} representa‐
200 tion makes it possible to identify a specific event handler when
201 many event handlers use the same callback module.
202
203 Args is any term that is passed as the argument to Mod‐
204 ule:init/1.
205
206 If Module:init/1 returns a correct value indicating successful
207 completion, the event manager adds the event handler and this
208 function returns ok. If Module:init/1 fails with Reason or re‐
209 turns {error,Reason}, the event handler is ignored and this
210 function returns {'EXIT',Reason} or {error,Reason}, respec‐
211 tively.
212
213 add_sup_handler(EventMgrRef, Handler, Args) -> Result
214
215 Types:
216
217 EventMgrRef = Name | {Name,Node} | {global,GlobalName} |
218 {via,Module,ViaName} | pid()
219 Name = Node = atom()
220 GlobalName = ViaName = term()
221 Handler = Module | {Module,Id}
222 Module = atom()
223 Id = term()
224 Args = term()
225 Result = ok | {'EXIT',Reason} | term()
226 Reason = term()
227
228 Adds a new event handler in the same way as add_handler/3, but
229 also supervises the connection by linking the event handler and
230 the calling process.
231
232 * If the calling process later terminates with Reason, the
233 event manager deletes any supervised event handlers by call‐
234 ing Module:terminate/2, then calls Module:handle_info/2 for
235 each remaining handler.
236
237 * If the event handler is deleted later, the event manager
238 sends a message {gen_event_EXIT,Handler,Reason} to the call‐
239 ing process. Reason is one of the following:
240
241 * normal, if the event handler has been removed because of a
242 call to delete_handler/3, or remove_handler has been re‐
243 turned by a callback function (see below).
244
245 * shutdown, if the event handler has been removed because
246 the event manager is terminating.
247
248 * {swapped,NewHandler,Pid}, if the process Pid has replaced
249 the event handler with another event handler NewHandler
250 using a call to swap_handler/3 or swap_sup_handler/3.
251
252 * A term, if the event handler is removed because of an er‐
253 ror. Which term depends on the error.
254
255 For a description of the arguments and return values, see
256 add_handler/3.
257
258 call(EventMgrRef, Handler, Request) -> Result
259 call(EventMgrRef, Handler, Request, Timeout) -> Result
260
261 Types:
262
263 EventMgrRef = Name | {Name,Node} | {global,GlobalName} |
264 {via,Module,ViaName} | pid()
265 Name = Node = atom()
266 GlobalName = ViaName = term()
267 Handler = Module | {Module,Id}
268 Module = atom()
269 Id = term()
270 Request = term()
271 Timeout = int()>0 | infinity
272 Result = Reply | {error,Error}
273 Reply = term()
274 Error = bad_module | {'EXIT',Reason} | term()
275 Reason = term()
276
277 Makes a synchronous call to event handler Handler installed in
278 event manager EventMgrRef by sending a request and waiting until
279 a reply arrives or a time-out occurs. The event manager calls
280 Module:handle_call/2 to handle the request.
281
282 For a description of EventMgrRef and Handler, see add_handler/3.
283
284 Request is any term that is passed as one of the arguments to
285 Module:handle_call/2.
286
287 Timeout is an integer greater than zero that specifies how many
288 milliseconds to wait for a reply, or the atom infinity to wait
289 indefinitely. Defaults to 5000. If no reply is received within
290 the specified time, the function call fails.
291
292 The return value Reply is defined in the return value of Mod‐
293 ule:handle_call/2. If the specified event handler is not in‐
294 stalled, the function returns {error,bad_module}. If the call‐
295 back function fails with Reason or returns an unexpected value
296 Term, this function returns {error,{'EXIT',Reason}} or {er‐
297 ror,Term}, respectively.
298
299 When this call fails it exits the calling process. The exit term
300 is on the form {Reason, Location} where Location =
301 {gen_event,call,ArgList}. See gen_server:call/3 that has a de‐
302 scription of relevant values for the Reason in the exit term.
303
304 check_response(Msg, ReqId) -> Result
305
306 Types:
307
308 Msg = term()
309 ReqId = request_id()
310 Response =
311 {reply, Reply :: term()} |
312 {error, {Reason :: term(), emgr_ref()}}
313 Result = Response | no_reply
314
315 Check if Msg is a response corresponding to the request identi‐
316 fier ReqId. The request must have been made by send_request/3.
317
318 If Msg is a response corresponding to ReqId the response is re‐
319 turned; otherwise, no_reply is returned and no cleanup is done,
320 and thus the function must be invoked repeatedly until a re‐
321 sponse is returned.
322
323 If the specified event handler is not installed, the function
324 returns {error,bad_module}. If the callback function fails with
325 Reason or returns an unexpected value Term, this function re‐
326 turns {error,{'EXIT',Reason}} or {error,Term}, respectively. If
327 the event manager dies before or during the request this func‐
328 tion returns {error,{Reason, EventMgrRef}}.
329
330 check_response(Msg, ReqIdCollection, Delete) -> Result
331
332 Types:
333
334 Msg = term()
335 ReqIdCollection = request_id_collection()
336 Delete = boolean()
337 Response =
338 {reply, Reply :: term()} |
339 {error, {Reason :: term(), emgr_ref()}}
340 Result =
341 {Response,
342 Label :: term(),
343 NewReqIdCollection :: request_id_collection()} |
344 no_request | no_reply
345
346 Check if Msg is a response corresponding to a request identifier
347 saved in ReqIdCollection. All request identifiers of ReqIdCol‐
348 lection must correspond to requests that have been made using
349 send_request/3 or send_request/5, and all requests must have
350 been made by the process calling this function.
351
352 The Label in the response equals the Label associated with the
353 request identifier that the response corresponds to. The Label
354 of a request identifier is associated when saving the request id
355 in a request identifier collection, or when sending the request
356 using send_request/5.
357
358 Compared to check_response/2, the returned result associated
359 with a specific request identifier or an exception associated
360 with a specific request identifier will be wrapped in a 3-tuple.
361 The first element of this tuple equals the value that would have
362 been produced by check_response/2, the second element equals the
363 Label associated with the specific request identifier, and the
364 third element NewReqIdCollection is a possibly modified request
365 identifier collection.
366
367 If ReqIdCollection is empty, the atom no_request will be re‐
368 turned. If Msg does not correspond to any of the request identi‐
369 fiers in ReqIdCollection, the atom no_reply is returned.
370
371 If Delete equals true, the association with Label will have been
372 deleted from ReqIdCollection in the resulting NewReqIdCollec‐
373 tion. If Delete equals false, NewReqIdCollection will equal Re‐
374 qIdCollection. Note that deleting an association is not for free
375 and that a collection containing already handled requests can
376 still be used by subsequent calls to check_response/3, re‐
377 ceive_response/3, and wait_response/3. However, without deleting
378 handled associations, the above calls will not be able to detect
379 when there are no more outstanding requests to handle, so you
380 will have to keep track of this some other way than relying on a
381 no_request return. Note that if you pass a collection only con‐
382 taining associations of already handled or abandoned requests to
383 check_response/3, it will always return no_reply.
384
385 delete_handler(EventMgrRef, Handler, Args) -> Result
386
387 Types:
388
389 EventMgrRef = Name | {Name,Node} | {global,GlobalName} |
390 {via,Module,ViaName} | pid()
391 Name = Node = atom()
392 GlobalName = ViaName = term()
393 Handler = Module | {Module,Id}
394 Module = atom()
395 Id = term()
396 Args = term()
397 Result = term() | {error,module_not_found} | {'EXIT',Reason}
398 Reason = term()
399
400 Deletes an event handler from event manager EventMgrRef. The
401 event manager calls Module:terminate/2 to terminate the event
402 handler.
403
404 For a description of EventMgrRef and Handler, see add_handler/3.
405
406 Args is any term that is passed as one of the arguments to Mod‐
407 ule:terminate/2.
408
409 The return value is the return value of Module:terminate/2. If
410 the specified event handler is not installed, the function re‐
411 turns {error,module_not_found}. If the callback function fails
412 with Reason, the function returns {'EXIT',Reason}.
413
414 notify(EventMgrRef, Event) -> ok
415 sync_notify(EventMgrRef, Event) -> ok
416
417 Types:
418
419 EventMgrRef = Name | {Name,Node} | {global,GlobalName} |
420 {via,Module,ViaName} | pid()
421 Name = Node = atom()
422 GlobalName = ViaName = term()
423 Event = term()
424
425 Sends an event notification to event manager EventMgrRef. The
426 event manager calls Module:handle_event/2 for each installed
427 event handler to handle the event.
428
429 notify/2 is asynchronous and returns immediately after the event
430 notification has been sent. sync_notify/2 is synchronous in the
431 sense that it returns ok after the event has been handled by all
432 event handlers.
433
434 For a description of EventMgrRef, see add_handler/3.
435
436 Event is any term that is passed as one of the arguments to Mod‐
437 ule:handle_event/2.
438
439 notify/1 does not fail even if the specified event manager does
440 not exist, unless it is specified as Name.
441
442 receive_response(ReqId, Timeout) -> Result
443
444 Types:
445
446 ReqId = request_id()
447 Timeout = response_timeout()
448 Response =
449 {reply, Reply :: term()} |
450 {error, {Reason :: term(), emgr_ref()}}
451 Result = Response | timeout
452
453 Receive a response corresponding to the request identifier Re‐
454 qId- The request must have been made by send_request/3 to the
455 gen_statem process. This function must be called from the same
456 process from which send_request/3 was made.
457
458 Timeout specifies how long to wait for a response. If no re‐
459 sponse is received within the specified time, the function re‐
460 turns timeout. Assuming that the server executes on a node sup‐
461 porting aliases (introduced in OTP 24) the request will also be
462 abandoned. That is, no response will be received after a time‐
463 out. Otherwise, a stray response might be received at a later
464 time.
465
466 The return value Reply is defined in the return value of Mod‐
467 ule:handle_call/3.
468
469 If the specified event handler is not installed, the function
470 returns {error,bad_module}. If the callback function fails with
471 Reason or returns an unexpected value Term, this function re‐
472 turns {error,{'EXIT',Reason}} or {error,Term}, respectively. If
473 the event manager dies before or during the request this func‐
474 tion returns {error,{Reason, EventMgrRef}}.
475
476 The difference between wait_response/2 and receive_response/2 is
477 that receive_response/2 abandons the request at timeout so that
478 a potential future response is ignored, while wait_response/2
479 does not.
480
481 receive_response(ReqIdCollection, Timeout, Delete) -> Result
482
483 Types:
484
485 ReqIdCollection = request_id_collection()
486 Timeout = response_timeout()
487 Delete = boolean()
488 Response =
489 {reply, Reply :: term()} |
490 {error, {Reason :: term(), emgr_ref()}}
491 Result =
492 {Response,
493 Label :: term(),
494 NewReqIdCollection :: request_id_collection()} |
495 no_request | timeout
496
497 Receive a response corresponding to a request identifier saved
498 in ReqIdCollection. All request identifiers of ReqIdCollection
499 must correspond to requests that have been made using send_re‐
500 quest/3 or send_request/5, and all requests must have been made
501 by the process calling this function.
502
503 The Label in the response equals the Label associated with the
504 request identifier that the response corresponds to. The Label
505 of a request identifier is associated when adding the request id
506 in a request identifier collection, or when sending the request
507 using send_request/5.
508
509 Compared to receive_response/2, the returned result associated
510 with a specific request identifier will be wrapped in a 3-tuple.
511 The first element of this tuple equals the value that would have
512 been produced by receive_response/2, the second element equals
513 the Label associated with the specific request identifier, and
514 the third element NewReqIdCollection is a possibly modified re‐
515 quest identifier collection.
516
517 If ReqIdCollection is empty, the atom no_request will be re‐
518 turned.
519
520 Timeout specifies how long to wait for a response. If no re‐
521 sponse is received within the specified time, the function re‐
522 turns timeout. Assuming that the server executes on a node sup‐
523 porting aliases (introduced in OTP 24) all requests identified
524 by ReqIdCollection will also be abandoned. That is, no responses
525 will be received after a timeout. Otherwise, stray responses
526 might be received at a later time.
527
528 The difference between receive_response/3 and wait_response/3 is
529 that receive_response/3 abandons the requests at timeout so that
530 potential future responses are ignored, while wait_response/3
531 does not.
532
533 If Delete equals true, the association with Label will have been
534 deleted from ReqIdCollection in the resulting NewReqIdCollec‐
535 tion. If Delete equals false, NewReqIdCollection will equal Re‐
536 qIdCollection. Note that deleting an association is not for free
537 and that a collection containing already handled requests can
538 still be used by subsequent calls to receive_response/3,
539 check_response/3, and wait_response/3. However, without deleting
540 handled associations, the above calls will not be able to detect
541 when there are no more outstanding requests to handle, so you
542 will have to keep track of this some other way than relying on a
543 no_request return. Note that if you pass a collection only con‐
544 taining associations of already handled or abandoned requests to
545 receive_response/3, it will always block until a timeout deter‐
546 mined by Timeout is triggered.
547
548 reqids_add(ReqId :: request_id(),
549 Label :: term(),
550 ReqIdCollection :: request_id_collection()) ->
551 NewReqIdCollection :: request_id_collection()
552
553 Saves ReqId and associates a Label with the request identifier
554 by adding this information to ReqIdCollection and returning the
555 resulting request identifier collection.
556
557 reqids_new() -> NewReqIdCollection :: request_id_collection()
558
559 Returns a new empty request identifier collection. A request
560 identifier collection can be utilized in order the handle multi‐
561 ple outstanding requests.
562
563 Request identifiers of requests made by send_request/3 can be
564 saved in a request identifier collection using reqids_add/3.
565 Such a collection of request identifiers can later be used in
566 order to get one response corresponding to a request in the col‐
567 lection by passing the collection as argument to receive_re‐
568 sponse/3, wait_response/3, or, check_response/3.
569
570 reqids_size/1 can be used to determine the amount of request
571 identifiers in a request identifier collection.
572
573 reqids_size(ReqIdCollection :: request_id_collection()) ->
574 integer() >= 0
575
576 Returns the amount of request identifiers saved in ReqIdCollec‐
577 tion.
578
579 reqids_to_list(ReqIdCollection :: request_id_collection()) ->
580 [{ReqId :: request_id(), Label :: term()}]
581
582 Returns a list of {ReqId, Label} tuples which corresponds to all
583 request identifiers with their associated labels present in the
584 ReqIdCollection collection.
585
586 send_request(EventMgrRef :: emgr_ref(),
587 Handler :: handler(),
588 Request :: term()) ->
589 ReqId :: request_id()
590
591 Sends an asynchronous call request Request to event handler Han‐
592 dler installed in the event manager identified by EventMgrRef
593 and returns a request identifier ReqId. The return value ReqId
594 shall later be used with receive_response/2, wait_response/2, or
595 check_response/2 to fetch the actual result of the request. Be‐
596 sides passing the request identifier directly to these func‐
597 tions, it can also be saved in a request identifier collection
598 using reqids_add/3. Such a collection of request identifiers can
599 later be used in order to get one response corresponding to a
600 request in the collection by passing the collection as argument
601 to receive_response/3, wait_response/3, or check_response/3. If
602 you are about to save the request identifier in a request iden‐
603 tifier collection, you may want to consider using send_request/5
604 instead.
605
606 The call gen_event:receive_response(gen_event:send_re‐
607 quest(EventMgrRef, Handler, Request), Timeout) can be seen as
608 equivalent to gen_event:call(EventMgrRef, Handler, Request,
609 Timeout), ignoring the error handling.
610
611 The event manager calls Module:handle_call/2 to handle the re‐
612 quest.
613
614 Request is any term that is passed as one of the arguments to
615 Module:handle_call/3.
616
617 send_request(EventMgrRef :: emgr_ref(),
618 Handler :: handler(),
619 Request :: term(),
620 Label :: term(),
621 ReqIdCollection :: request_id_collection()) ->
622 NewReqIdCollection :: request_id_collection()
623
624 Sends an asynchronous call request Request to event handler Han‐
625 dler installed in the event manager identified by EventMgrRef.
626 The Label will be associated with the request identifier of the
627 operation and added to the returned request identifier collec‐
628 tion NewReqIdCollection. The collection can later be used in or‐
629 der to get one response corresponding to a request in the col‐
630 lection by passing the collection as argument to receive_re‐
631 sponse/3, wait_response/3, or, check_response/3.
632
633 The same as calling gen_event:reqids_add(gen_event:send_re‐
634 quest(EventMgrRef, Handler, Request), Label, ReqIdCollection),
635 but calling send_request/5 is slightly more efficient.
636
637 start() -> Result
638 start(EventMgrName | Options) -> Result
639 start(EventMgrName, Options) -> Result
640
641 Types:
642
643 EventMgrName = {local,Name} | {global,GlobalName} | {via,Mod‐
644 ule,ViaName}
645 Name = atom()
646 GlobalName = ViaName = term()
647 Options = [Option]
648 Option = {debug,Dbgs} | {timeout,Time} | {hibernate_af‐
649 ter,HibernateAfterTimeout} | {spawn_opt,SOpts}
650 Dbgs = [Dbg]
651 Dbg = trace | log | statistics | {log_to_file,FileName} |
652 {install,{Func,FuncState}}
653 SOpts = [term()]
654 Result = {ok,Pid} | {error,{already_started,OtherPid}} | {er‐
655 ror,timeout}
656 Pid = OtherPid = pid()
657
658 Creates a stand-alone event manager process, that is, an event
659 manager that is not part of a supervision tree and thus has no
660 supervisor.
661
662 For a description of the arguments and return values, see
663 start_link/0,1.
664
665 start_link() -> Result
666 start_link(EventMgrName | Options) -> Result
667 start_link(EventMgrName, Options) -> Result
668
669 Types:
670
671 EventMgrName = {local,Name} | {global,GlobalName} | {via,Mod‐
672 ule,ViaName}
673 Name = atom()
674 GlobalName = ViaName = term()
675 Options = [Option]
676 Option = {debug,Dbgs} | {timeout,Time} | {hibernate_af‐
677 ter,HibernateAfterTimeout} | {spawn_opt,SOpts}
678 Dbgs = [Dbg]
679 Dbg = trace | log | statistics | {log_to_file,FileName} |
680 {install,{Func,FuncState}}
681 SOpts = [term()]
682 Result = {ok,Pid} | {error,{already_started,OtherPid}} | {er‐
683 ror,timeout}
684 Pid = OtherPid = pid()
685
686 Creates an event manager process as part of a supervision tree.
687 The function is to be called, directly or indirectly, by the su‐
688 pervisor. For example, it ensures that the event manager is
689 linked to the caller (supervisor).
690
691 * If EventMgrName={local,Name}, the event manager is regis‐
692 tered locally as Name using register/2.
693
694 * If EventMgrName={global,GlobalName}, the event manager is
695 registered globally as GlobalName using global:regis‐
696 ter_name/2. If no name is provided, the event manager is not
697 registered.
698
699 * If EventMgrName={via,Module,ViaName}, the event manager reg‐
700 isters with the registry represented by Module. The Module
701 callback is to export the functions register_name/2, unreg‐
702 ister_name/1, whereis_name/1, and send/2, which are to be‐
703 have as the corresponding functions in global. Thus,
704 {via,global,GlobalName} is a valid reference.
705
706 * If option {hibernate_after,HibernateAfterTimeout} is
707 present, the gen_event process awaits any message for Hiber‐
708 nateAfterTimeout milliseconds and if no message is received,
709 the process goes into hibernation automatically (by calling
710 proc_lib:hibernate/3).
711
712 If the event manager is successfully created, the function re‐
713 turns {ok,Pid}, where Pid is the pid of the event manager.
714
715 If a process with the specified EventMgrName exists already, the
716 function returns {error,{already_started,OtherPid}}, where Oth‐
717 erPid is the pid of that process, and the event manager process
718 exits with reason normal.
719
720 If the event manager fails to start within the specified start
721 timeout {timeout,Time}, which is very unlikely since the start
722 does not interact with other processes, the function returns
723 {error,timeout} and the failed event manager is killed with
724 exit(_, kill).
725
726 If start_link/1,2 returns {error,_}, the started event manager
727 process has terminated. If an 'EXIT' message was delivered to
728 the calling process (due to the process link), that message has
729 been consumed.
730
731 Warning:
732 Before OTP 26.0, if the started event manager failed to register
733 its name, this founction could return {error,{al‐
734 ready_started,OtherPid}} before the started event manager
735 process had terminated so starting again might fail because the
736 registered name was not yet unregistered, and an 'EXIT' message
737 could arrive later to the process calling this function.
738
739 But if the start timed out, this function killed the started
740 event manager process and returned {error,timeout}, and then the
741 process link {'EXIT',Pid,killed} message was consumed.
742
743 The start was made synchronous in OTP 26.0 and the guarantee was
744 implemented that no process link 'EXIT' message from a failed
745 start will linger in the caller's inbox.
746
747
748 start_monitor() -> Result
749 start_monitor(EventMgrName | Options) -> Result
750 start_monitor(EventMgrName, Options) -> Result
751
752 Types:
753
754 EventMgrName = {local,Name} | {global,GlobalName} | {via,Mod‐
755 ule,ViaName}
756 Name = atom()
757 GlobalName = ViaName = term()
758 Options = [Option]
759 Option = {debug,Dbgs} | {timeout,Time} | {hibernate_af‐
760 ter,HibernateAfterTimeout} | {spawn_opt,SOpts}
761 Dbgs = [Dbg]
762 Dbg = trace | log | statistics | {log_to_file,FileName} |
763 {install,{Func,FuncState}}
764 SOpts = [term()]
765 Result = {ok,{Pid,Mon}} | {error,{already_started,OtherPid}}
766 | {error,timeout}
767 Pid = OtherPid = pid()
768
769 Creates a stand-alone event manager process, that is, an event
770 manager that is not part of a supervision tree (and thus has no
771 supervisor) and atomically sets up a monitor to the newly cre‐
772 ated process.
773
774 For a description of the arguments and return values, see
775 start_link/0,1. Note that the return value on successful start
776 differs from start_link/3,4. start_monitor/3,4 will return
777 {ok,{Pid,Mon}} where Pid is the process identifier of the
778 process, and Mon is a reference to the monitor set up to monitor
779 the process. If the start is not successful, the caller will be
780 blocked until the DOWN message has been received and removed
781 from the message queue.
782
783 stop(EventMgrRef) -> ok
784 stop(EventMgrRef, Reason, Timeout) -> ok
785
786 Types:
787
788 EventMgrRef = Name | {Name,Node} | {global,GlobalName} |
789 {via,Module,ViaName} | pid()
790 Name = Node = atom()
791 GlobalName = ViaName = term()
792 Reason = term()
793 Timeout = int()>0 | infinity
794
795 Orders event manager EventMgrRef to exit with the specifies Rea‐
796 son and waits for it to terminate. Before terminating, gen_event
797 calls Module:terminate(stop,...) for each installed event han‐
798 dler.
799
800 The function returns ok if the event manager terminates with the
801 expected reason. Any other reason than normal, shutdown, or
802 {shutdown,Term} causes an error report to be issued using log‐
803 ger(3). The default Reason is normal.
804
805 Timeout is an integer greater than zero that specifies how many
806 milliseconds to wait for the event manager to terminate, or the
807 atom infinity to wait indefinitely. Defaults to infinity. If the
808 event manager has not terminated within the specified time, the
809 call exits the calling process with reason timeout.
810
811 If the process does not exist, the call exits the calling
812 process with reason noproc, and with reason {nodedown,Node} if
813 the connection fails to the remote Node where the server runs.
814
815 For a description of EventMgrRef, see add_handler/3.
816
817 swap_handler(EventMgrRef, {Handler1,Args1}, {Handler2,Args2}) -> Result
818
819 Types:
820
821 EventMgrRef = Name | {Name,Node} | {global,GlobalName} |
822 {via,Module,ViaName} | pid()
823 Name = Node = atom()
824 GlobalName = ViaName = term()
825 Handler1 = Handler2 = Module | {Module,Id}
826 Module = atom()
827 Id = term()
828 Args1 = Args2 = term()
829 Result = ok | {error,Error}
830 Error = {'EXIT',Reason} | term()
831 Reason = term()
832
833 Replaces an old event handler with a new event handler in event
834 manager EventMgrRef.
835
836 For a description of the arguments, see add_handler/3.
837
838 First the old event handler Handler1 is deleted. The event man‐
839 ager calls Module1:terminate(Args1, ...), where Module1 is the
840 callback module of Handler1, and collects the return value.
841
842 Then the new event handler Handler2 is added and initiated by
843 calling Module2:init({Args2,Term}), where Module2 is the call‐
844 back module of Handler2 and Term is the return value of Mod‐
845 ule1:terminate/2. This makes it possible to transfer information
846 from Handler1 to Handler2.
847
848 The new handler is added even if the the specified old event
849 handler is not installed, in which case Term=error, or if Mod‐
850 ule1:terminate/2 fails with Reason, in which case
851 Term={'EXIT',Reason}. The old handler is deleted even if Mod‐
852 ule2:init/1 fails.
853
854 If there was a supervised connection between Handler1 and a
855 process Pid, there is a supervised connection between Handler2
856 and Pid instead.
857
858 If Module2:init/1 returns a correct value, this function returns
859 ok. If Module2:init/1 fails with Reason or returns an unexpected
860 value Term, this function returns {error,{'EXIT',Reason}} or
861 {error,Term}, respectively.
862
863 swap_sup_handler(EventMgrRef, {Handler1,Args1}, {Handler2,Args2}) ->
864 Result
865
866 Types:
867
868 EventMgrRef = Name | {Name,Node} | {global,GlobalName} |
869 {via,Module,ViaName} | pid()
870 Name = Node = atom()
871 GlobalName = ViaName = term()
872 Handler1 = Handler 2 = Module | {Module,Id}
873 Module = atom()
874 Id = term()
875 Args1 = Args2 = term()
876 Result = ok | {error,Error}
877 Error = {'EXIT',Reason} | term()
878 Reason = term()
879
880 Replaces an event handler in event manager EventMgrRef in the
881 same way as swap_handler/3, but also supervises the connection
882 between Handler2 and the calling process.
883
884 For a description of the arguments and return values, see
885 swap_handler/3.
886
887 wait_response(ReqId, WaitTime) -> Result
888
889 Types:
890
891 ReqId = request_id()
892 WaitTime = response_timeout()
893 Response =
894 {reply, Reply :: term()} |
895 {error, {Reason :: term(), emgr_ref()}}
896 Result = Response | timeout
897
898 Wait for a response corresponding to the request identifier Re‐
899 qId. The request must have been made by send_request/3 to the
900 gen_statem process. This function must be called from the same
901 process from which send_request/3 was made.
902
903 WaitTime specifies how long to wait for a response. If no re‐
904 sponse is received within the specified time, the function re‐
905 turns timeout and no cleanup is done, and thus the function can
906 be invoked repeatedly until a reply is returned.
907
908 The return value Reply is defined in the return value of Mod‐
909 ule:handle_call/3.
910
911 If the specified event handler is not installed, the function
912 returns {error,bad_module}. If the callback function fails with
913 Reason or returns an unexpected value Term, this function re‐
914 turns {error,{'EXIT',Reason}} or {error,Term}, respectively. If
915 the event manager dies before or during the request this func‐
916 tion returns {error,{Reason, EventMgrRef}}.
917
918 The difference between receive_response/2 and wait_response/2 is
919 that receive_response/2 abandons the request at timeout so that
920 a potential future response is ignored, while wait_response/2
921 does not.
922
923 wait_response(ReqIdCollection, WaitTime, Delete) -> Result
924
925 Types:
926
927 ReqIdCollection = request_id_collection()
928 WaitTime = response_timeout()
929 Delete = boolean()
930 Response =
931 {reply, Reply :: term()} |
932 {error, {Reason :: term(), emgr_ref()}}
933 Result =
934 {Response,
935 Label :: term(),
936 NewReqIdCollection :: request_id_collection()} |
937 no_request | timeout
938
939 Wait for a response corresponding to a request identifier saved
940 in ReqIdCollection. All request identifiers of ReqIdCollection
941 must correspond to requests that have been made using send_re‐
942 quest/3 or send_request/5, and all requests must have been made
943 by the process calling this function.
944
945 The Label in the response equals the Label associated with the
946 request identifier that the response corresponds to. The Label
947 of a request identifier is associated when saving the request id
948 in a request identifier collection, or when sending the request
949 using send_request/5.
950
951 Compared to wait_response/2, the returned result associated with
952 a specific request identifier or an exception associated with a
953 specific request identifier will be wrapped in a 3-tuple. The
954 first element of this tuple equals the value that would have
955 been produced by wait_response/2, the second element equals the
956 Label associated with the specific request identifier, and the
957 third element NewReqIdCollection is a possibly modified request
958 identifier collection.
959
960 If ReqIdCollection is empty, no_request will be returned. If no
961 response is received before the WaitTime timeout has triggered,
962 the atom timeout is returned. It is valid to continue waiting
963 for a response as many times as needed up until a response has
964 been received and completed by check_response(), receive_re‐
965 sponse(), or wait_response().
966
967 The difference between receive_response/3 and wait_response/3 is
968 that receive_response/3 abandons requests at timeout so that po‐
969 tential future responses are ignored, while wait_response/3 does
970 not.
971
972 If Delete equals true, the association with Label will have been
973 deleted from ReqIdCollection in the resulting NewReqIdCollec‐
974 tion. If Delete equals false, NewReqIdCollection will equal Re‐
975 qIdCollection. Note that deleting an association is not for free
976 and that a collection containing already handled requests can
977 still be used by subsequent calls to wait_response/3, check_re‐
978 sponse/3, and receive_response/3. However, without deleting han‐
979 dled associations, the above calls will not be able to detect
980 when there are no more outstanding requests to handle, so you
981 will have to keep track of this some other way than relying on a
982 no_request return. Note that if you pass a collection only con‐
983 taining associations of already handled or abandoned requests to
984 wait_response/3, it will always block until a timeout determined
985 by WaitTime is triggered and then return no_reply.
986
987 which_handlers(EventMgrRef) -> [Handler]
988
989 Types:
990
991 EventMgrRef = Name | {Name,Node} | {global,GlobalName} |
992 {via,Module,ViaName} | pid()
993 Name = Node = atom()
994 GlobalName = ViaName = term()
995 Handler = Module | {Module,Id}
996 Module = atom()
997 Id = term()
998
999 Returns a list of all event handlers installed in event manager
1000 EventMgrRef.
1001
1002 For a description of EventMgrRef and Handler, see add_handler/3.
1003
1005 The following functions are to be exported from a gen_event callback
1006 module.
1007
1009 Module:code_change(OldVsn, State, Extra) -> {ok, NewState}
1010
1011 Types:
1012
1013 OldVsn = Vsn | {down, Vsn}
1014 Vsn = term()
1015 State = NewState = term()
1016 Extra = term()
1017
1018 Note:
1019 This callback is optional, so callback modules need not export
1020 it. If a release upgrade/downgrade with Change={advanced,Extra}
1021 specified in the .appup file is made when code_change/3 isn't
1022 implemented the event handler will crash with an undef error
1023 reason.
1024
1025
1026 This function is called for an installed event handler that is
1027 to update its internal state during a release upgrade/downgrade,
1028 that is, when the instruction {update,Module,Change,...}, where
1029 Change={advanced,Extra}, is specified in the .appup file. For
1030 more information, see OTP Design Principles.
1031
1032 For an upgrade, OldVsn is Vsn, and for a downgrade, OldVsn is
1033 {down,Vsn}. Vsn is defined by the vsn attribute(s) of the old
1034 version of the callback module Module. If no such attribute is
1035 defined, the version is the checksum of the Beam file.
1036
1037 State is the internal state of the event handler.
1038
1039 Extra is passed "as is" from the {advanced,Extra} part of the
1040 update instruction.
1041
1042 The function is to return the updated internal state.
1043
1044 Module:format_status(Status) -> NewStatus
1045
1046 Types:
1047
1048 Status = format_status()
1049 NewStatus = format_status()
1050
1051 Note:
1052 This callback is optional, so event handler modules need not ex‐
1053 port it. If a handler does not export this function, the
1054 gen_event module uses the handler state directly for the pur‐
1055 poses described below.
1056
1057 If this callback is exported but fails, to hide possibly sensi‐
1058 tive data, the default function will instead return the fact
1059 that format_status/1 has crashed.
1060
1061
1062 This function is called by a gen_event process in the following
1063 situations:
1064
1065 * One of sys:get_status/1,2 is invoked to get the gen_event
1066 status.
1067
1068 * The event handler terminates abnormally and gen_event logs
1069 an error.
1070
1071 This callback is used to limit the status of the event handler
1072 returned by sys:get_status/1,2 or sent to logger.
1073
1074 The callback gets a map Status describing the current status and
1075 shall return a map NewStatus with the same keys, but it may
1076 transform some values.
1077
1078 Two possible use cases for this callback is to remove sensitive
1079 information from the state to prevent it from being printed in
1080 log files, or to compact large irrelevant status items that
1081 would only clutter the logs.
1082
1083 format_status(Status) ->
1084 maps:map(
1085 fun(state,State) ->
1086 maps:remove(private_key, State);
1087 (message,{password, _Pass}) ->
1088 {password, removed};
1089 (_,Value) ->
1090 Value
1091 end, Status).
1092
1093
1094 Module:format_status(Opt, [PDict, State]) -> Status
1095
1096 Types:
1097
1098 Opt = normal | terminate
1099 PDict = [{Key, Value}]
1100 State = term()
1101 Status = term()
1102
1103 Warning:
1104 This callback is deprecated, in new code use format_status/1.
1105 If a format_status/1 callback exists, then this function will
1106 never be called.
1107
1108
1109 Note:
1110 This callback is optional, so event handler modules need not ex‐
1111 port it. If a handler does not export this function, the
1112 gen_event module uses the handler state directly for the pur‐
1113 poses described below.
1114
1115
1116 This function is called by a gen_event process in the following
1117 situations:
1118
1119 * One of sys:get_status/1,2 is invoked to get the gen_event
1120 status. Opt is set to the atom normal for this case.
1121
1122 * The event handler terminates abnormally and gen_event logs
1123 an error. Opt is set to the atom terminate for this case.
1124
1125 This function is useful for changing the form and appearance of
1126 the event handler state for these cases. An event handler call‐
1127 back module wishing to change the the sys:get_status/1,2 return
1128 value as well as how its state appears in termination error
1129 logs, exports an instance of format_status/2 that returns a term
1130 describing the current state of the event handler.
1131
1132 PDict is the current value of the process dictionary of
1133 gen_event.
1134
1135 State is the internal state of the event handler.
1136
1137 The function is to return Status, a term that change the details
1138 of the current state of the event handler. Any term is allowed
1139 for Status. The gen_event module uses Status as follows:
1140
1141 * When sys:get_status/1,2 is called, gen_event ensures that
1142 its return value contains Status in place of the state term
1143 of the event handler.
1144
1145 * When an event handler terminates abnormally, gen_event logs
1146 Status in place of the state term of the event handler.
1147
1148 One use for this function is to return compact alternative state
1149 representations to avoid that large state terms are printed in
1150 log files.
1151
1152 Module:handle_call(Request, State) -> Result
1153
1154 Types:
1155
1156 Request = term()
1157 State = term()
1158 Result = {ok,Reply,NewState} | {ok,Reply,NewState,hibernate}
1159 | {swap_handler,Reply,Args1,NewState,Handler2,Args2}
1160 | {remove_handler, Reply}
1161 Reply = term()
1162 NewState = term()
1163 Args1 = Args2 = term()
1164 Handler2 = Module2 | {Module2,Id}
1165 Module2 = atom()
1166 Id = term()
1167
1168 Whenever an event manager receives a request sent using
1169 call/3,4, this function is called for the specified event han‐
1170 dler to handle the request.
1171
1172 Request is the Request argument of call/3,4.
1173
1174 State is the internal state of the event handler.
1175
1176 The return values are the same as for Module:handle_event/2 ex‐
1177 cept that they also contain a term Reply, which is the reply to
1178 the client as the return value of call/3,4.
1179
1180 Module:handle_event(Event, State) -> Result
1181
1182 Types:
1183
1184 Event = term()
1185 State = term()
1186 Result = {ok,NewState} | {ok,NewState,hibernate}
1187 | {swap_handler,Args1,NewState,Handler2,Args2} | remove_han‐
1188 dler
1189 NewState = term()
1190 Args1 = Args2 = term()
1191 Handler2 = Module2 | {Module2,Id}
1192 Module2 = atom()
1193 Id = term()
1194
1195 Whenever an event manager receives an event sent using notify/2
1196 or sync_notify/2, this function is called for each installed
1197 event handler to handle the event.
1198
1199 Event is the Event argument of notify/2/sync_notify/2.
1200
1201 State is the internal state of the event handler.
1202
1203 * If {ok,NewState} or {ok,NewState,hibernate} is returned, the
1204 event handler remains in the event manager with the possible
1205 updated internal state NewState.
1206
1207 * If {ok,NewState,hibernate} is returned, the event manager
1208 also goes into hibernation (by calling proc_lib:hiber‐
1209 nate/3), waiting for the next event to occur. It is suffi‐
1210 cient that one of the event handlers return {ok,NewState,hi‐
1211 bernate} for the whole event manager process to hibernate.
1212
1213 * If {swap_handler,Args1,NewState,Handler2,Args2} is returned,
1214 the event handler is replaced by Handler2 by first calling
1215 Module:terminate(Args1,NewState) and then Mod‐
1216 ule2:init({Args2,Term}), where Term is the return value of
1217 Module:terminate/2. For more information, see swap_han‐
1218 dler/3.
1219
1220 * If remove_handler is returned, the event handler is deleted
1221 by calling Module:terminate(remove_handler,State).
1222
1223 Module:handle_info(Info, State) -> Result
1224
1225 Types:
1226
1227 Info = term()
1228 State = term()
1229 Result = {ok,NewState} | {ok,NewState,hibernate}
1230 | {swap_handler,Args1,NewState,Handler2,Args2} | remove_han‐
1231 dler
1232 NewState = term()
1233 Args1 = Args2 = term()
1234 Handler2 = Module2 | {Module2,Id}
1235 Module2 = atom()
1236 Id = term()
1237
1238 Note:
1239 This callback is optional, so callback modules need not export
1240 it. The gen_event module provides a default implementation of
1241 this function that logs about the unexpected Info message, drops
1242 it and returns {ok, State}.
1243
1244
1245 This function is called for each installed event handler when an
1246 event manager receives any other message than an event or a syn‐
1247 chronous request (or a system message).
1248
1249 Info is the received message.
1250
1251 In particular, this callback will be made when a process termi‐
1252 nated after calling add_sup_handler/3. Any event handler at‐
1253 tached to an event manager which in turn has a supervised han‐
1254 dler should expect callbacks of the shape Module:han‐
1255 dle_info({'EXIT', Pid, Reason}, State).
1256
1257 For a description of State and possible return values, see Mod‐
1258 ule:handle_event/2.
1259
1260 Module:init(InitArgs) -> {ok,State} | {ok,State,hibernate} | {er‐
1261 ror,Reason}
1262
1263 Types:
1264
1265 InitArgs = Args | {Args,Term}
1266 Args = Term = term()
1267 State = term()
1268 Reason = term()
1269
1270 Whenever a new event handler is added to an event manager, this
1271 function is called to initialize the event handler.
1272
1273 If the event handler is added because of a call to add_handler/3
1274 or add_sup_handler/3, InitArgs is the Args argument of these
1275 functions.
1276
1277 If the event handler replaces another event handler because of a
1278 call to swap_handler/3 or swap_sup_handler/3, or because of a
1279 swap return tuple from one of the other callback functions, Ini‐
1280 tArgs is a tuple {Args,Term}, where Args is the argument pro‐
1281 vided in the function call/return tuple and Term is the result
1282 of terminating the old event handler, see swap_handler/3.
1283
1284 If successful, the function returns {ok,State} or {ok,State,hi‐
1285 bernate}, where State is the initial internal state of the event
1286 handler.
1287
1288 If {ok,State,hibernate} is returned, the event manager goes into
1289 hibernation (by calling proc_lib:hibernate/3), waiting for the
1290 next event to occur.
1291
1292 Module:terminate(Arg, State) -> term()
1293
1294 Types:
1295
1296 Arg = Args | {stop,Reason} | stop | remove_handler
1297 | {error,{'EXIT',Reason}} | {error,Term}
1298 Args = Reason = Term = term()
1299
1300 Note:
1301 This callback is optional, so callback modules need not export
1302 it. The gen_event module provides a default implementation with‐
1303 out cleanup.
1304
1305
1306 Whenever an event handler is deleted from an event manager, this
1307 function is called. It is to be the opposite of Module:init/1
1308 and do any necessary cleaning up.
1309
1310 If the event handler is deleted because of a call to delete_han‐
1311 dler/3, swap_handler/3, or swap_sup_handler/3, Arg is the Args
1312 argument of this function call.
1313
1314 Arg={stop,Reason} if the event handler has a supervised connec‐
1315 tion to a process that has terminated with reason Reason.
1316
1317 Arg=stop if the event handler is deleted because the event man‐
1318 ager is terminating.
1319
1320 The event manager terminates if it is part of a supervision tree
1321 and it is ordered by its supervisor to terminate. Even if it is
1322 not part of a supervision tree, it terminates if it receives an
1323 'EXIT' message from its parent.
1324
1325 Arg=remove_handler if the event handler is deleted because an‐
1326 other callback function has returned remove_handler or {re‐
1327 move_handler,Reply}.
1328
1329 Arg={error,Term} if the event handler is deleted because a call‐
1330 back function returned an unexpected value Term, or Arg={er‐
1331 ror,{'EXIT',Reason}} if a callback function failed.
1332
1333 State is the internal state of the event handler.
1334
1335 The function can return any term. If the event handler is
1336 deleted because of a call to gen_event:delete_handler/3, the re‐
1337 turn value of that function becomes the return value of this
1338 function. If the event handler is to be replaced with another
1339 event handler because of a swap, the return value is passed to
1340 the init function of the new event handler. Otherwise the return
1341 value is ignored.
1342
1344 supervisor(3), sys(3)
1345
1346
1347
1348Ericsson AB stdlib 5.1.1 gen_event(3)