// SingleTimer.h: interface for the CSingleTimer class.
// 定时器类,既被其他类继承,也可以单独使用
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_TIMER_H__92B2B013_0302_446A_B4EB_D6C1D18E8C08__INCLUDED_)
#define AFX_TIMER_H__92B2B013_0302_446A_B4EB_D6C1D18E8C08__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <windows.h> // 使用HANDLE等类型
#include <stdexcept> // 使用std::runtime_error类
#define INVALID_DURATION_TIME -1
#define DEFAULT_DURATION_TIME 1000 // 缺省定时时间为1000毫秒
class CSingleTimer;
typedef void (CSingleTimer:: * TIME_OUT_NOTIFY_FUNC)(); // 时间到通知函数(本类派生类的成员函数)
typedef void (* TIME_OUT_NOTIFY_CALLBACK)(); // 时间到通知函数(全局函数)
///////////////////////////////////////////////////////////////////////////////
#pragma warning( push )
#pragma warning( disable :4290)
class CSingleTimer
{
public:
CSingleTimer(unsigned DurTime=DEFAULT_DURATION_TIME, TIME_OUT_NOTIFY_FUNC NotFunc=NULL) throw(std::runtime_error); // 继承使用方式
CSingleTimer(unsigned DurTime, TIME_OUT_NOTIFY_CALLBACK NotCallBck) throw(std::runtime_error); // 单独使用方式
virtual ~CSingleTimer(); // 可能被继承,至少一个虚函数
void WaitForTimeOut();
bool StartTimer(int DurTime=INVALID_DURATION_TIME, TIME_OUT_NOTIFY_FUNC NotFunc=NULL); // 继承使用方式
bool StartTimer(int DurTime, TIME_OUT_NOTIFY_CALLBACK NotCallBck); // 单独使用方式
private:
static void LoopRunThreadFunc(CSingleTimer * pThisClass);
void StopTimerLoop();
bool StartTimerLoop();
void Initialize() throw(std::runtime_error);
private:
unsigned m_DurationTime; // 定时的时间长度(单位: ms)
TIME_OUT_NOTIFY_FUNC m_pTimeOutNotifyFunc; // 时间到通知函数
TIME_OUT_NOTIFY_CALLBACK m_pTimeOutNotifyCallBackFunc; // 时间到回调(全局)函数
HANDLE m_evtStartTimer; // 定时器启动事件
HANDLE m_evtTimeOut; // 定时器时间到事件
HANDLE m_evtTiming; // 定时器正处在定时中的状态标记
HANDLE m_hThread; // 线程启动后获得的句柄,也是线程是否在运行的标记
BOOL m_bThreadExitFlag; // 线程是否退出运行标记
CRITICAL_SECTION * m_pcsThdExitFlg; // 存取是否能运行标记的临界变量
};
#pragma warning( pop )
#endif // !defined(AFX_TIMER_H__92B2B013_0302_446A_B4EB_D6C1D18E8C08__INCLUDED_)