使用evtimer_new申请一个定时器,并指定定时器回调函数。
#include <iostream>
#include <event2/event.h>
#include <signal.h>
using namespace std;
static timeval t1 = {1, 0};
void timer1(int sockfd, short what, void* arg){
cout << "[timer1]" << flush;
event* ev = (event*) arg;
if(!evtimer_pending(ev, &t1)){
evtimer_del(ev);
evtimer_add(ev, &t1);
}
}
void timer2(int sockfd, short what, void* arg){
cout << "[timer2]" << endl;
}
int main(int argc, char* argv[]){
//忽略管道信号,,发送数据给已经关闭的socket
if(signal(SIGPIPE, SIG_IGN) == SIG_ERR){
return 1;
}
event_base* base = event_base_new();
cout << "test timer" << endl;
//定时器,非持久事件
event* timer_ev = evtimer_new(base, timer1, event_self_cbarg());
if(!timer_ev){
cout << "evtimer_new failed!" << endl;
return 1;
}
evtimer_add(timer_ev, &t1);
// 持久事件
static timeval t2;
t2.tv_sec = 1;
t2.tv_usec = 200000;//微秒
event* persist_timer = event_new(base, -1, EV_PERSIST, timer2, 0);
event_add(persist_timer, &t2);
//进入事件主循环
event_base_dispatch(base);
event_base_free(base);
}
编写makefile
test_timer:test_timer.cpp
g++ $^ -o $@ -levent
make即可