企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## libevent 实现定时器流程 1. 首先初始化libevent库,并保存返回的指针 ``` struct event_base * base = event_init(); ``` >实际上这一步相当于初始化一个Reactor实例;在初始化libevent后,就可以注册事件了。 2. 初始化事件event,设置回调函数和关注的事件 ,事实上这等价于调用event_set(&ev, -1, 0, timer_cb, NULL); ``` evtimer_set(&ev, timer_cb, NULL); ``` 3. 设置event从属的event_base ,这一步相当于指明event要注册到哪个event\_base实例上; ``` event_base_set(base, &ev);  ``` 4. 是正式的添加事件的时候了 ``` event_add(&ev, timeout); ``` 基本信息都已设置完成,只要简单的调用event_add()函数即可完成,其中timeout是定时值; 这一步相当于调用Reactor::register_handler()函数注册事件。 5. 程序进入无限循环,等待就绪事件并执行事件处理 ``` event_base_dispatch(base); ``` ## 完整的示例代码 ``` #include <iostream> #include "event.h" struct timeval tv; struct event ev; static void time_cb(evutil_socket_t fd, short event, void* arg) { std::cout << "timer wakeup" << std::endl; event_add(&ev, &tv); // reschedule timer } int main() { struct event_base* base = event_base_new(); tv.tv_sec = 2; tv.tv_usec = 0; // event *timeout = event_new(base, -1, EV_PERSIST|EV_TIMEOUT, time_cb, NULL); evtimer_set(&ev, time_cb, nullptr); event_base_set(base, &ev); event_add(&ev, &tv); event_base_dispatch(base); return 1; } ``` ## 还有第二种定时器的方法 定义一个定时器事件,使用event_new()创建了一个定时器事件.替换上述的步骤2和3 ``` struct event *event_new(struct event_base *, evutil_socket_t, short, event_callback_fn, void *); ``` 完整示例代码 ``` #include <iostream> #include "event.h" struct timeval tv; struct event ev; static void time_cb(evutil_socket_t fd, short event, void* arg) { std::cout << "timer wakeup" << std::endl; //event_add(&ev, &tv); // reschedule timer } int main() { struct event_base* base = event_base_new(); tv.tv_sec = 2; tv.tv_usec = 0; event* ev = event_new(base, -1, EV_PERSIST|EV_TIMEOUT, time_cb, NULL); // evtimer_set(&ev, time_cb, nullptr); //event_base_set(base, &ev); event_add(ev, &tv); event_base_dispatch(base); return 1; } ```