定时器实现方案

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(); ... };

  

posted @ 2025-12-30 10:17  流逝的轻风  阅读(1)  评论(0)    收藏  举报