定时器系统

来源:互联网 发布:压缩感知算法 编辑:程序博客网 时间:2024/05/18 20:06

Rzyom定时器系统由三个类组成:

class CTimer;class CTimerEvent;class CTimerManager;

CTimerEvent          用于用户派生自己的事件处理类,重新实现定时回调接口timerCallback(),处理相应事件。


CTimer                    通用定时器类,设置定时时长,多久之后回调timerCallback()。

                                  如果这个对象被销毁其回调将被自动取消。 

                                  一个计时器只能设置一个触发时间,第二次设置将覆盖以前的时间。 


CTimerManager    这是一个单例,在tickUpdate()中触发时间到了的CTimerEvent.timerCallback() 。


注:该系统的唯一要求是,CTimerManager:: tickUpdate()需要在每个游戏循环中调用。


使用方法&例程:

class CMyClass;class CMyTimerEvent;class CMyTimerEvent: public CTimerEvent{public:CMyTimerEvent(CMyClass* parent);void timerCallback(CTimer* owner);private:CMyClass* _Parent;}class CMyClass{public:void startTimer(){// set the timer to trigger in 5000 millisecond_Timer.setRemaining(5000,new CMyTimerEvent(this));}void doSomething(CTimerEvent* event){nlinfo("hello world");// set the timer to trigger in 2000 millisecond with the same event handler_Timer.setRemaining(2000,event);}private:CMyTimer _Timer;};void CMyTimerEvent::CMyTimerEvent(CMyClass* parent){_Parent=parent;}void CMyTimerEvent::timerCallback(CTimer* owner){_Parent->doSomething(this);}


这个定时器系统的精度与服务器每帧的执行时间有关,默认为100毫秒。


CTimerEvent将定时时间换算成游戏循环圈数,hash后存于一个vector中,之后每次游戏循环检查 _EventVectors[uint8(fps&0xff)]。

// the type of the event vector for a given time hashtypedef std::vector<NLMISC::CSmartPtr<CTimerEvent> > TEventVector;TEventVector _EventVectors[256];







0 0