ACE学习之定时器(Timer)
定时器(Timer)
在事件超时的时候适当的调用事件处理器的handle_timeout()方法.为调度这样的定时器,反应器拥有一个schedule_timer()的方法.该方法接受事件处理器,以及以ACE_Time_Value对象形式出现的延迟对味参数.此外,可以指定时间间隔,使定时器在它超时后自动恢复 .
反应器在内部维护ACE_Timer_Queue,它以定时器要被调度的顺序对它们进行维护。实际使用的用于保存定时器的数据结构可以通过反应器的set_timer_queue()方法进行改变。反应器有若干不同的定时器结构可用,包括定时器轮(timer wheel)、定时器堆(timer heap)和哈希式定时器轮(hashed timer wheel)。
设置定时器:
#include "ace/Time_Value.h" #include "ace/Log_Msg.h" #include "ace/Synch.h" #include "ace/Reactor.h" #include "ace/Event_Handler.h" class wjtimer : public ACE_Event_Handler { public: virtual int handle_timeout(const ACE_Time_Value ¤t_time, const void *act /* = 0 */) { const int *num = ACE_static_cast(const int*,act); ACE_DEBUG((LM_DEBUG, ACE_TEXT("%d "),num)); return 0; } protected: private: }; int Start() { wjtimer *timer = new wjtimer; ACE_Time_Value tv(5),tv2(3); ACE_Reactor::instance()->schedule_timer(timer,(const int*)44,tv,tv2); while(1) ACE_Reactor::instance()->handle_events(); return 0; }
Wjtimer的handle_timeout用来处理定时器到期的函数,schedule_timer传入一个事件处理器的句柄,参数,开始延迟时间和恢复时间.它返回一个唯一的定时器标识符.
ACE提供了一组主动的定时器队列类,它不仅封装了基于OS的定时器机制,还会在自己私有的控制线程中运行定时器事件循环,所以叫主动定时器队列.
定义:
typedef ACE_Thread_Timer_Queue_Adapter<ACE_Timer_Heap>ActiveTimer;
ActiveTimer适配器允许你指定任何一种具体的定时器队列,充当主动定时器的底层定时器队列.
class CBB : public ACE_Event_Handler { private: int id_; public: CBB(int id) : id_(id){} virtual int handle_timeout(const ACE_Time_Value ¤t_time, const void *act /* = 0 */) { ACE_TRACE(ACE_TEXT("CBB::handle_timeout ")); ACE_DEBUG((LM_DEBUG, ACE_TEXT("Expiry handled by thread %t id=%d "),id_)); return 0; } }; //要创建一个定时器回调处理器,在事件处理器上的handle_timeout方法被分派. int Start() { ACE_DEBUG((LM_DEBUG, ACE_TEXT("The main thread %t has started "))); ActiveTimer atimer; atimer.activate(); CBB cb1(1); CBB cb2(2); int arg1 = 1; int arg2 = 2; const ACE_Time_Value curr_tv = ACE_OS::gettimeofday(); ACE_Time_Value interval = ACE_Time_Value(8,1000); ACE_Time_Value tv(3); long id1 = atimer.schedule(&cb1,&arg1,curr_tv+tv,interval); /*ACE_Time_Value tvv(5); long id2 = atimer.schedule(&cb2,&arg2,curr_tv+tvv,interval);*/ ACE_Thread_Manager::instance()->wait(); return 0; }
北京德胜门中医院精神科http://www.bjdsmyysjk120.com/
北京德胜门中医院精神科http://www.bjdsmyy120.com/