打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
ACE定时器

每一秒钟打印一行

http://www.tuicool.com/articles/Zb263e

计时器的打开和关闭封装

http://andylin02.iteye.com/blog/440572


自己写的简单计时器:程序开始之后2秒钟之后执行第一次到时触发的动作,以后每隔一秒钟都会执行相同的动作;当执行总次数到达3次之后就终止计时,整个程序退出,并停止事件监听,释放资源

  1. #include <iostream>  
  2. #include "ace/Log_Msg.h"  
  3. #include "ace/Event_Handler.h"  
  4. #include "ace/Reactor.h"  
  5. #include "ace/Thread_Manager.h"  
  6.   
  7. bool stop_event_loop = false;//是否需要终止计时器服务  
  8.   
  9. class My_Timer_Handler : public ACE_Event_Handler  
  10. {  
  11. public:  
  12.     My_Timer_Handler(const int delay,const int interval);  
  13.     ~My_Timer_Handler();  
  14.     int handle_timeout(const ACE_Time_Value& , const void *act /* = 0 */);//计时器到期后执行的回调函数  
  15. private:  
  16.     int n_;//循环计时的次数  
  17.     long time_handle_;//在计时器队列中的ID  
  18. };  
  19.   
  20. My_Timer_Handler::My_Timer_Handler(const int delay,const int interval):n_(0)  
  21. {  
  22.     std::cout<<"My_Timer_Handler()"<<std::endl;  
  23.     this->reactor(ACE_Reactor::instance());  
  24.     this->time_handle_ = this->reactor()->schedule_timer(this,//在这里注册定时器  
  25.         0,  
  26.         ACE_Time_Value(delay),//程序一开始延迟delay秒开始首次执行到期函数  
  27.         ACE_Time_Value(interval));//循环计时,每隔interval秒重复执行  
  28. }  
  29.   
  30. My_Timer_Handler::~My_Timer_Handler()  
  31. {  
  32.     std::cout<<"~My_Timer_Handler()"<<std::endl;  
  33. }  
  34.   
  35.   
  36. int My_Timer_Handler::handle_timeout(const ACE_Time_Value& , const void *act /* = 0 */)  
  37. {  
  38.     if (++this->n_>3)  
  39.     {  
  40.         ACE_Reactor::instance()->cancel_timer(this->time_handle_);  
  41.         stop_event_loop = true;  
  42.         std::cout<<"cancle_timer"<<std::endl;  
  43.     }  
  44.     else  
  45.     {  
  46.         std::cout<<"my timer handler handled timeout"<<std::endl;  
  47.     }  
  48.   
  49.     return 0;  
  50. }  
  51.   
  52. int main(int argc, char* argv[])  
  53. {  
  54.       
  55.     My_Timer_Handler my_handle(2,1);  
  56.   
  57.     while (true)  
  58.     {  
  59.         if (stop_event_loop)  
  60.         {  
  61.             std::cout<<"stop handle time"<<std::endl;  
  62.             break;  
  63.         }  
  64.         ACE_Reactor::instance()->handle_events();  
  65.     }  
  66.   
  67.     return 0;  
  68. }  



运行结果如下:

My_Timer_Handler()
my timer handler handled timeout
my timer handler handled timeout
my timer handler handled timeout
cancle_timer
stop handle time
~My_Timer_Handler()
请按任意键继续. . .


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
ACE学习之定时器(Timer)
Scheduler,Handler和Event类的关系
【译】Implementing Software Timers By: Don Libes...
android几种定时器机制及区别(转载整理)
初学者:ACE学习
Linux定时器(计时器)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服