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