C++主循环计时器
C++ main loop timer
我的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 的最后一个参数,以便每当计时器滴答作响时,它都会调用您的函数本身。
相关文章:
- Linux的Cpp上的计时器
- Ardunio UNO解决了多个重叠的定时器循环
- 提升 ASIO 无法识别计时器对象
- 提升 asio 并发计时器取消问题与链
- 使用单体计时器的pthread_cond_timedwait有时会比预期晚超时
- 窗口中的微秒计时器
- 计时器是否从另一个线程启动?
- 如何在 c++ 中创建计时器
- C++回调计时器实现
- 在计时器或主线程外部的命令上销毁/替换线程
- 如何制作每秒从 30 乘 1 倒计时的计时器?
- 循环计时器线程
- C++ 而循环计时器的准确性差异很大
- 是否可以创建一个跳过循环中函数的计时器
- 如何在C++中创建一个循环,运行一个计时器并允许用户同时输入(非阻塞用户输入)
- 升压计时器在循环中的结果相同"for"?
- While在c++中使用计时器循环
- 在已经运行的循环上添加另一个计时器
- 每次循环迭代重置计时器
- C++主循环计时器