C++ 定时每天十二点做某事

        获取当前的时间,需要的仅仅是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());
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值