libevent timer定时器

来源:互联网 发布:什么是淘宝店铺首页 编辑:程序博客网 时间:2024/06/05 04:47
每隔一秒循环执行回调函数#include <iostream>#include <event2/event.h>struct cb_arg{    struct event *ev;    struct timeval tv;};void timeout_cb(int fd, short event, void *params){    puts("111");    struct cb_arg *arg = (struct cb_arg*)params;    struct event *ev = arg->ev;    struct timeval tv = arg->tv;    evtimer_add(ev, &tv);}int main(){    struct event_base *base = event_base_new();    struct event *timeout = NULL;    struct timeval tv = {1, 0};    struct cb_arg arg;    timeout = evtimer_new(base, timeout_cb, &arg);    arg.ev = timeout;    arg.tv = tv;    evtimer_add(timeout, &tv);    event_base_dispatch(base);    evtimer_del(timeout);    return 0;}

或者:

让事件变为持久的,这样在执行完回调后事件处于未决状态。

事件的几个状态:

1.new -> 已初始化状态

2.add -> 未决状态

3.有信号 -> 激活状态,这时候会触发回调

4.回调执行之后 -> 非未决状态,如果new的时候有EV_PERSIST标记此时是未决状态。


#include <iostream>#include <event2/event.h>void timeout_cb(int fd, short event, void *params){    puts("111");}int main(){    struct event_base *base = event_base_new();    struct event *timeout = NULL;    struct timeval tv = {1, 0};    timeout = event_new(base, -1, EV_PERSIST, timeout_cb, NULL);    evtimer_add(timeout, &tv);    event_base_dispatch(base);    evtimer_del(timeout);    return 0;}