首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C++ Boost ASIO简单周期定时器?

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

Stack Overflow用户
提问于 2010-11-24 21:56:16
回答 5查看 50.9K关注 0票数 27

我想要一个非常简单的周期计时器来调用我的代码每50ms。我可以做一个一直睡眠50ms的线程(但这很痛苦)……我可以开始研究Linux API来制作定时器(但它不能移植)……

我想使用boost..我只是不确定这有没有可能。boost是否提供此功能?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-11-24 22:01:32

Boosts教程中的第二个示例解释了这一点。

你可以在here上找到它。

之后,使用check the 3rd example查看如何使用周期性的时间间隔再次调用它

票数 19
EN

Stack Overflow用户

发布于 2015-07-03 02:32:01

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

代码语言:javascript
复制
#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()来设置一个新的过期时间非常重要,否则计时器将立即触发,因为它的当前到期时间已经过期。

票数 28
EN

Stack Overflow用户

发布于 2019-04-04 00:17:17

来进一步扩展这个简单的例子。它会像注释中所说的那样阻塞执行,所以如果你想运行更多的io_services,你应该像这样在线程中运行它们。

代码语言:javascript
复制
boost::asio::io_service io_service;
boost::asio::io_service service2;
timer.async_wait(tick);
boost::thread_group threads;
threads.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));
service2.run();
threads.join_all();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4267546

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档