C++主循环计时器

C++ main loop timer

本文关键字:计时器 循环 C++      更新时间:2023-10-16

我的C++程序有一个主循环,该循环一直运行到程序说它完成为止。 在主循环中,我希望能够在特定的时间间隔内使某些事情发生。喜欢这个:

int main()
{
    while(true)
    {
        if(ThirtySecondsHasPassed())
        {
            doThis();
        }
        doEverythingElse();
    }
    return 0;
}

在这种情况下,我希望每三十秒调用一次doThis(),如果不需要调用它,则允许主循环继续并处理其他所有内容。

我该怎么做?另请记住,该程序旨在连续运行数天,数周甚至数月。

这是一个更通用的类,您可以在其中使用单独的计时器。

class Timer{
public:
    Timer(time_type interval) : interval(interval) {
        reset();
    }
    bool timedOut(){
        if(get_current_time() >= deadline){
            reset();
            return true;
        }
        else return false;
    }
    void reset(){
        deadline = get_current_time() + interval;
    }
private:
    time_type deadline;
    const time_type interval;
}

可能是迄今为止最大的矫枉过正,但 Boost.Asio 呢?

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
void doThisProxy(const boost::system::error_code& /*e*/,
    boost::asio::deadline_timer* t)
{
  doThis();
  t->expires_at(t->expires_at() + boost::posix_time::seconds(30));
  t->async_wait(boost::bind(doThisProxy, boost::asio::placeholders::error, t));
}
int main()
{
  boost::asio::io_service io;
  boost::asio::deadline_timer t(io, boost::posix_time::seconds(30));
  t.async_wait(boost::bind(doThisProxy, boost::asio::placeholders::error, &t));
  io.run();
}

如果你的程序要在Windows系统中编译和运行,你也可以使用一些Windows处理程序,如下所示:

SetTimer(hwnd,             // handle to main window 
IDT_TIMER1,            // timer identifier 
30000,                 // 10-second interval 
(TIMERPROC) NULL);     // no timer callback 
while (1)
{
    if (! PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
    {
        doeverythingelse();                   
    }
    if (WM_QUIT == msg.message)
    {
        break;
    }
    if(WM_TIMER == msg.message)
    {
         if(IDT_TIMER1 == msg.wParam)
              do30secInterval();
    }               
}

您还可以传递一些函数作为 SetTimer 的最后一个参数,以便每当计时器滴答作响时,它都会调用您的函数本身。