這是一個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;
}