获取当前的时间,需要的仅仅是hour、minute、second。以及定时的是时间点,例如:24 : 00 :00;
使用 定时的时间 减去 当前时间,然后使用Sleep将线程睡眠等待。这样就不需要重复的判断去执行。
代码:
class CTime
{
public:
CTime();
CTime(const int32_t& nHour, const int32_t& nMinute, const int32_t& nSecond) :m_nTimeValue((nHour * 60 * 60) + (nMinute * 60) + (nSecond)) {}
CTime(const int32_t& nTimeValue) : m_nTimeValue(nTimeValue) {}
CTime(const Time& tTime) : m_nTimeValue((tTime.hour() * 60 * 60) + (tTime.minute() * 60) + (tTime.second())) {}
CTime& operator+= (int32_t nTimeValue)
{
m_nTimeValue += nTimeValue;
return *this;
}
DWORD operator- (const CTime& ctTime) const
{
//例 : this : 23 --- target : 13
if (this->m_nTimeValue > ctTime.m_nTimeValue)
{
return this->m_nTimeValue - ctTime.m_nTimeValue;
}
// 例 : this : 13 ---- taget : 23
else if(this->m_nTimeValue < ctTime.m_nTimeValue)
{
return (24 * 60 * 60) - ctTime.m_nTimeValue + this->m_nTimeValue;
}
//this == taget
else
{
return 1;
}
}
int32_t Hour() const { return m_nTimeValue / 60 / 60; }
int32_t Minute() const { return (m_nTimeValue / 60) % 60; }
int32_t Second() const { return m_nTimeValue % 60; }
int32_t TimeValue() const { return m_nTimeValue; }
private:
//时间
int32_t m_nTimeValue;
};
void CSqliteManager::ThreadTimingCleanSql()
{
//由于Time获取的是UTC时间,想要使用当前的时间 就需要加上当前时区的偏移 (返回秒)
int32_t tz = Timezone::tzd();
//一直执行的线程 不允许终止
while (true)
{
try
{
CTime ctNow(std::move(Time())); //当前时间
CTime ctTiming(15, 48, 00); //指定的定时时间
ctNow += tz; //加上时区时间
DWORD dwSleep = (ctTiming - ctNow) ; //指定的时间 与 当前时间的差距
Sleep(dwSleep * 1000); //睡眠到定时的时间点起床执行相应代码
cout << "ThreadTimingCleanSql" << endl;
}
catch (const Exception& e)
{
poco_error_f1(ITCLOG, "ThreadTimingCleanSql [%s]", e.displayText());
}
}
}