C++ Boost ASIO 简单的周期性定时器?

标签 c++ linux boost boost-asio

我想要一个非常简单的周期性计时器来每 50 毫秒调用一次我的代码。我可以制作一个一直休眠 50 毫秒的线程(但这很痛苦)...我可以开始研究用于制作计时器的 Linux API(但它不是可移植的)...

我希望喜欢使用 boost.. 我只是不确定这是否可能。 boost 是否提供此功能?

最佳答案

一个非常简单但功能齐全的示例:

#include <iostream>
#include <boost/asio.hpp>

boost::asio::io_service io_service;
boost::posix_time::seconds interval(1);  // 1 second
boost::asio::deadline_timer timer(io_service, interval);

void tick(const boost::system::error_code& /*e*/) {

    std::cout << "tick" << std::endl;

    // Reschedule the timer for 1 second in the future:
    timer.expires_at(timer.expires_at() + interval);
    // Posts the timer event
    timer.async_wait(tick);
}

int main(void) {

    // Schedule the timer for the first time:
    timer.async_wait(tick);
    // Enter IO loop. The timer will fire for the first time 1 second from now:
    io_service.run();
    return 0;
}

请注意,调用 expires_at() 设置新的到期时间非常重要,否则计时器将立即触发,因为它的当前到期时间已经到期。

关于C++ Boost ASIO 简单的周期性定时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4267546/

相关文章:

c++ - 如何使图片适合静态控件 vc++ win32

c++ - 使用 printf 将 em-dash 打印到控制台窗口?

linux - 执行错误的 shell 命令卡住时如何恢复?

linux - awk:根据给定列的前 3 个不同值选择行

c++ - 使用 zlib 压缩 boost 二进制文件

c++ - 在 boost geometry c++ 库中我添加的点的顺序有关系吗?

c++ - 启动类函数作为线程失去引用

c++ - c中用于动态分配的新char命令

.net - NAnt 和双平台构建 - 在 Windows 和 Mono/Linux 上构建的最佳方式

c++ - boost::any_cast<double>(any&) 可以 boost 吗?