对libevent中Timer的分析: (~provos/libevent/doxygen-2.0.1/) Timer: libevent can also be used to create timers that invoke a callback after a certain amount of time has expired. The function prepares an event struct to be used as a timer. To activate the timer, call . Timers can be deactivated by calling .
2.event_base_set函数原型: int event_base_set(struct event_base *eb, struct event *ev) Associate a different event base with an event. 将一个event关联到一个不同的event base. 也就说我们可以将一个event关联到不同的event base.
3.evtimer_add函数原型: int evtimer_add(struct event *ev, const struct timeval *timeout) Add an event to the set of monitored events. 将一个event加入到被监视的事件集合。 evan event struct initialized via timeoutthe maximum amount of time to wait for the event, or NULL to wait forever.
4.evtimer_del函数原型: #define evtimer_del(ev) event_del(ev) so: int evtimer_del(struct event * ev) Delete a timer event. ev the event struct to be disabled
main 执行的流程为: event_handler()第一次执行,将event_handler自己设为回调函数,在event_handler()第一次执行完成之后退出,1秒中之后,main_base又会触发event_handler再执行一次,第二次以及之后event_handler的执行,是先将上一次的event struct删除,然后初始化再重新加入,这样就周而复始,就实现了每隔1秒钟set_current_time()函数和print函数就执行一次从而输出时间。
总结一下: 1. 首先调用event_base_new(或者event_init,推荐调用前者),对libevent进行唯一的一次初始化。 before using any of the functions in the library, you must call or to perform one-time initialization of the libevent library.
2. 然后调用evtimer_set初始化一个struct event结构体,也就是将利用evtimer_set的参数(即回调函数和回调函数的参数)填充struct event 结构体。 The function prepares an event struct to be used as a timer。
再调用evtimer_add()将被evtimer_set初始化的struct event结构体加入到被监视的集合中. To activate the timer, call .
删除一个event调用evtimer_del() Timers can be deactivated by calling .
3.最后调用event_base_loop()或者event_base_dispatch()或者event_dispatch(),推荐调用第一个,最后一个是非线程安全的版本。 从而开始处理事件集合,开始对event集合进行监视monitor. Loop to process events.
In order to process events, an application needs to call . event_base_dispatch() is threadsafe event dispatching loop. event_base_loop() is a more flexible version of .