本文主要是介绍libevent timer定时器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
每隔一秒循环执行回调函数
#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;
}
这篇关于libevent timer定时器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!