每一秒鐘打印一行
http://www./articles/Zb263e
計(jì)時(shí)器的打開和關(guān)閉封裝
http://andylin02./blog/440572
自己寫的簡(jiǎn)單計(jì)時(shí)器:程序開始之后2秒鐘之后執(zhí)行第一次到時(shí)觸發(fā)的動(dòng)作,以后每隔一秒鐘都會(huì)執(zhí)行相同的動(dòng)作;當(dāng)執(zhí)行總次數(shù)到達(dá)3次之后就終止計(jì)時(shí),整個(gè)程序退出,并停止事件監(jiān)聽,釋放資源
- #include <iostream>
- #include "ace/Log_Msg.h"
- #include "ace/Event_Handler.h"
- #include "ace/Reactor.h"
- #include "ace/Thread_Manager.h"
-
- bool stop_event_loop = false;//是否需要終止計(jì)時(shí)器服務(wù)
-
- class My_Timer_Handler : public ACE_Event_Handler
- {
- public:
- My_Timer_Handler(const int delay,const int interval);
- ~My_Timer_Handler();
- int handle_timeout(const ACE_Time_Value& , const void *act /* = 0 */);//計(jì)時(shí)器到期后執(zhí)行的回調(diào)函數(shù)
- private:
- int n_;//循環(huán)計(jì)時(shí)的次數(shù)
- long time_handle_;//在計(jì)時(shí)器隊(duì)列中的ID
- };
-
- My_Timer_Handler::My_Timer_Handler(const int delay,const int interval):n_(0)
- {
- std::cout<<"My_Timer_Handler()"<<std::endl;
- this->reactor(ACE_Reactor::instance());
- this->time_handle_ = this->reactor()->schedule_timer(this,//在這里注冊(cè)定時(shí)器
- 0,
- ACE_Time_Value(delay),//程序一開始延遲delay秒開始首次執(zhí)行到期函數(shù)
- ACE_Time_Value(interval));//循環(huán)計(jì)時(shí),每隔interval秒重復(fù)執(zhí)行
- }
-
- My_Timer_Handler::~My_Timer_Handler()
- {
- std::cout<<"~My_Timer_Handler()"<<std::endl;
- }
-
-
- int My_Timer_Handler::handle_timeout(const ACE_Time_Value& , const void *act /* = 0 */)
- {
- if (++this->n_>3)
- {
- ACE_Reactor::instance()->cancel_timer(this->time_handle_);
- stop_event_loop = true;
- std::cout<<"cancle_timer"<<std::endl;
- }
- else
- {
- std::cout<<"my timer handler handled timeout"<<std::endl;
- }
-
- return 0;
- }
-
- int main(int argc, char* argv[])
- {
-
- My_Timer_Handler my_handle(2,1);
-
- while (true)
- {
- if (stop_event_loop)
- {
- std::cout<<"stop handle time"<<std::endl;
- break;
- }
- ACE_Reactor::instance()->handle_events();
- }
-
- return 0;
- }
運(yùn)行結(jié)果如下:
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()
請(qǐng)按任意鍵繼續(xù). . .
|