当前位置:   article > 正文

使用libevent编写定时器_libevent 多线程定时器

libevent 多线程定时器

       Libevent如何安装请参考这篇博客 windows 上安装 libevent 

       有了定时器,我们便可以定时的做一些任务

       

  1. struct event_base *baseEv; //事件
  2. struct event *ev;
  3. struct timeval tv; //定时器
  4. void time_cb(int fd,short _event,void *argc)
  5. {
  6. cout<<"timer wakeup"<<endl;
  7. evtimer_add(ev,&tv);/*重新添加定时器*/
  8. }
  9. static void MyTime()
  10. {
  11. WSADATA WSAData; /*初始化WINDOWS socket库*/
  12. WSAStartup(0x101, &WSAData);
  13. struct event_base *base = event_base_new();//初始化libevent库,相当于初始化一个Reactior,就可以注册事件了.
  14. tv.tv_sec=5; //间隔
  15. tv.tv_usec=0;
  16. ev = evtimer_new(base,time_cb,NULL);//初始化关注的事件,并设置回调函数
  17. event_add(ev,&tv);//注册事件 相当于调用Reactor::register_handler()函数注册事件
  18. event_base_dispatch(base);//进入消息循环和消息分发
  19. }
  20. int main(int argc, char **argv)
  21. {
  22. MyTime();
  23. return 0;
  24. }
调用回调函数后,如果希望定时器继续起作用,那么就需要重新添加

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/742783
推荐阅读
相关标签
  

闽ICP备14008679号