libevent代码例子----定时器

来源:互联网 发布:冰点文库软件下载 编辑:程序博客网 时间:2024/06/06 02:17

libevent最简单的一个小例子:定时器的使用



  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3. #include <sys/time.h>  
  4. #include <event.h>  
  5. // 定时事件回调函数   
  6. void onTime(int sock, short event, void *arg)   
  7. {   
  8.     printf("Hello,World!\n");  
  9.   
  10.     struct timeval tv;   
  11.     tv.tv_sec = 1;   
  12.     tv.tv_usec = 0;   
  13.     // 重新添加定时事件(定时事件触发后默认自动删除)   
  14.     event_add((struct event*)arg, &tv);   
  15. }   
  16.      
  17. int main()   
  18. {   
  19.     // 初始化   
  20.     event_init();   
  21.      
  22.     struct event ev_time;   
  23.     // 设置定时事件   
  24.     evtimer_set(&ev_time, onTime, &ev_time);   
  25.      
  26.     struct timeval tv;   
  27.     tv.tv_sec = 1;   
  28.     tv.tv_usec = 0;   
  29.     // 添加定时事件   
  30.     event_add(&ev_time, &tv);   
  31.      
  32.     // 事件循环   
  33.     event_dispatch();   
  34.      
  35.     return 0;   




编译:gcc example1.c -o example1 -levent



运行,就可以在终端看到每隔两秒输出"Hello,World!"了。




参考:

 libevent学习笔记 一、基础知识
http://blog.csdn.net/majianfei1023/article/details/46485705





0 0
原创粉丝点击