简介
- gen_event 是OTP 中的事件管理器,可以向现有或者我们生成的一个gen_event 进程注册增加或者减少一个事件处理(a callback module), 当我们向该进程notify一个事件时,每个注册的事件处理都会收到该事件,然后进行相应的处理。
- Note that an event manager does trap exit signals automatically
下面是它的回调
模块函数简单介绍
start_link/0
start/0创建一个event manager process
add_handler(EventMgrRef, Handler, Args) -> Result
增加一个新的事件处理(event handler)给EventMgrRef(event manager). event manager 将会调用 Module:init/1 来初始化 event_handler
add_sup_handler(EventMgrRef, Handler, Args) -> Result
和add_handler 一样,但是会监控event handler 和 the calling process 之间的联系。
- 如果the calling process 终止, event manager process 将会call the module:terminate({stop, Reason} 来删除 event handler
- 如果 event handler 被 删除了, event manager 将会发送 一个消息 {gen_event_EXIT, Handler, Reason} 给 the call prrocess。 具体原因参考官方文档
notify(EventMgrRef, Event) -> ok
sync_notify(EventMgrRef, Event) -> ok发送一个 event notification 给EventMgrRef(the event manager) , event manager 将会对每一个注册的event handler 调用 Module:handle_event/2 来处理 the event
note: notify 是异步的,而sync_notify 是同步的call(EventMgrRef, Handler, Reqest) -> Result
call(EventMgrRef, Handler, Request, Timeout) -> Result发送一个同步的call 给event manager, the event manager 将会对每一个注册的event handle 调用相应的handle_call。 而the call process 将会一直阻塞直到返回或者timeout
delete_handler(EventMgrRef, Handler, Args) -> Result
从一个event manager 中删除一个event handler。 the event manager 将会调用module:terminate/2 来终止event handler
swap_handler(EventMgrRef, {Handler1, Args1}, {Handler2, Args2}) -> Result
用于取代一个旧的Event handler
首先Module1:terminate(Args1,..) , 然后Module:init({Args2, Term} 。这个Term 是Module1:terminate/2的返回值。swap_handler(EventMgrRef, {Handler1, Args1}, {Handler2, Args2}) -> Result
和 swap_handler 一样,但是会监控Handler2 和 the calling process 的connection。
which_handlers(EventMgrRef) -> [Handler]
返回event manager管理的所有的event handler
stop(EventMgrRef) -> ok
stop(EventMgrRef, Reason, Timeout) -> ok调用每个event handler 的module:terminate