定时器实现方案
1.头文件
#include "time.h"
#ifndef LH_UINT64
#ifdef LH_OS_WIN32
#if defined(__GNUC__)
#define LH_UINT64 unsigned long long
#else
#define LH_UINT64 unsigned __int64
#endif
#else
#define LH_UINT64 unsigned long long
#endif
#endif
#ifndef LH_MAXS
#define LH_MAXS(t) ((t)(((LH_UINT64)-1) >> ((8 - sizeof(t)) * 8 + 1)))
#endif
#ifndef LH_MAXU
#define LH_MAXU(t) ((t)(((LH_UINT64)-1) >> ((8 - sizeof(t)) * 8)))
#endif
class TimeCountDown {
public:
TimeCountDown(void);
~TimeCountDown(void);
static unsigned int GetTickCount();
static bool TimeIsOver(unsigned int n32MilliSecond);
};
2.实现文件
#include "TimeCountDown.h"
TimeCountDown::TimeCountDown(void) {
}
TimeCountDown::~TimeCountDown(void) {
}
unsigned int TimeCountDown::GetTickCount() {
struct timespec stTs;
clock_gettime(CLOCK_MONOTONIC, &stTs);
return (stTs.tv_sec * 1000 + stTs.tv_nsec / 1000000);
}
bool TimeCountDown::TimeIsOver(unsigned int n32Tick) {
unsigned int nNowTime;
nNowTime = GetTickCount();
if((nNowTime == n32Tick)
|| ((nNowTime > n32Tick) && ((nNowTime - n32Tick) < ((LH_MAXU(unsigned int) >> 1))))
|| ((nNowTime < n32Tick) && ((n32Tick - nNowTime) > ((LH_MAXU(unsigned int) >> 1))))
)
{
return true;
}
return false;
}
3.用法
if (TimeCountDown::TimeIsOver(m_iSycTime + m_iSycMoveTargetSpan * 1000)) { m_iSycTime = TimeCountDown::GetTickCount(); ... };
浙公网安备 33010602011771号