在不怎么了解libevent的情况下,看到timer这个关键字想到可以用来做定时任务,官方资料也不齐全,就从代码里看到了TIMEOUT字样,这么说来应该是支持timeout了,那interval呢,貌似没有发现更好的办法,姑且在timeout里再timeout一次吧,留代码备用。
1 #include2 #include 3 #include 4 5 typedef struct { 6 struct timeval tv; 7 struct event * ev; 8 } timer_param_t; 9 10 11 void timer_task(int fd, short events, void * ctx) {12 printf("...\n");13 14 timer_param_t * param = (timer_param_t *) ctx;15 evtimer_add(param->ev, ¶m->tv);16 }17 18 int main() {19 struct event_base * base;20 base = event_base_new();21 if(!base) {22 printf("open event base error\n");23 return -1;24 }25 timer_param_t * param = calloc(1, sizeof(timer_param_t));26 param->ev = evtimer_new(base, timer_task, param);27 param->tv.tv_sec = 1;28 evtimer_add(param->ev, ¶m->tv);29 int err = event_base_dispatch(base);30 printf("error = %d\n", err);31 return 0;32 }
编译:gcc -o timer timer.c -levent