定时器基本应用
1:首先初始化libevent库,并保存返回的指针
struct event_base *base=event_base_new();
2:定义两个结构体,分别代表事件和定时器值
struct event timeout;//定时器事件
struct timeval tv; //定时器值
3:将事件和event_base绑定
event_assign(&timeout,base,-1,flags,timeout_cb,(void*)&timeout);
flags参数代表了事件标志int flags=0;
4:在创建定时器时间时,使用的是struct eventtimeout,也可以用event_new函数动态分配,就不需要event_assign
struct event *timeout;
timeout=evsignal_new(base,-1,flags,timeout_cv,(void*)&timeout);
在分配后可以用event_free来释放
5:添加事件
event_add(&timeout,&tv);
6:程序进入无线循环,等待就绪事件并执行事件处理
event_base_dispatch(base);
//exp1:2s定时器
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <event2/event.h>
#include <event2/event_struct.h>
static void timeout_cb(evutil_socket_t fd,short event,void *arg)
{
struct event *timeout;
timeout=(struct event*) arg;
struct timeval tv;
evutil_timerclear(&tv);
tv.tv_sec=2;
event_add(timeout,&tv);
printf("OnTimer\n");
}
int main()
{
struct event_base *base=event_base_new();
struct event timeout;
struct timeval tv;
int flags=0;
event_assign(&timeout,base,-1,flags,timeout_cb,(void*)&timeout);
evutil_timerclear(&tv);
tv.tv_sec=2;
tv.tv_usec=0;
event_add(&timeout,&tv);
event_base_dispatch(base);
return 0;
}
//exp2:
#include <event2/event.h>#include <event2/util.h>
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <memory.h>
using namespace std;
struct EventTimerParam
{
struct timeval tv;
void *ctx;
void *evt;
};
void libevent_tick_event_cv(evutil_socket_t fd,short events,void *ctx)
{
printf("function1 is called\n");
EventTimerParam *pParam=(EventTimerParam*)ctx;
pParam->tv.tv_sec=1;
evtimer_add((struct event*)pParam->evt,&pParam->tv);
}
int main()
{
struct event_base *base;
base=event_base_new();
if(!base)
return -1;
EventTimerParam *pTimerParam=(EventTimerParam*)malloc(sizeof(EventTimerParam));
memset(pTimerParam,0,sizeof(EventTimerParam));
struct event *ev=evtimer_new(base,libevent_tick_event_cv,pTimerParam);
pTimerParam->evt=ev;
pTimerParam->ctx=NULL;
pTimerParam->tv.tv_sec=1;
evtimer_add(ev,&pTimerParam->tv);
int err=event_base_dispatch(base);
cout<<"err="<<err<<endl;
return 0;
}