这是一个libevent实现的简单定时器功能,并可以用函数指针封装函数来使外部来调用。
#include <iostream>
#include <event.h>
using namespace std;
static char test_char[100] = "begin test";
struct event ev;
struct timeval tv;
typedef void (*LiveStatusCB)(const char* ret); //可以设置一个函数指针为外部提供调用
void lsc(const char* ret) { //外部提供的可调用的函数
cout << "ret=" << ret << endl;
}
LiveStatusCB fff = lsc; //设置函数指针
void fun_test(int fd, short n, void * a) { //时间回调函数
cout << "fd=" << fd << endl;
// evtimer_del(&ev);
evtimer_add(&ev, &tv); //循环添加事件
cout << (char *) a << endl;
char* xxx = "this is a test";
(*fff)(xxx); //运行函数
}
int main() {
const char* libevent_version = event_get_version();
cout << "it is start =" <<libevent_version<< endl;
event_init();
evtimer_set(&ev, fun_test, test_char); //设置时间事件
tv.tv_sec = 5;
tv.tv_usec = 0;
evtimer_add(&ev, &tv); //添加时间事件
event_dispatch(); //开启监控
cout << "it is over " << endl;
return 0;
}