繁体   English   中英

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

[英]C++ Boost ASIO simple periodic timer?

我想要一个非常简单的周期性定时器,每50ms调用一次我的代码。 我可以创建一个一直睡眠50ms的线程(但这很痛苦)...我可以开始研究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()来设置新的到期时间非常重要,否则计时器将立即触发,因为它的当前到期时间已经过期。

关于Boosts Asio教程的第二个例子解释了它。
你可以在这里找到它。

之后, 请检查第3个示例 ,了解如何使用定期时间间隔再次调用它

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

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();

由于我在先前的答案中遇到了一些问题,这是我的例子:

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>

void print(const boost::system::error_code&, boost::asio::deadline_timer* t,int* count)
{
    if (*count < 5)
    {
        std::cout << *count << std::endl;
        ++(*count);
        t->expires_from_now(boost::posix_time::seconds(1));
        t->async_wait(boost::bind(print, boost::asio::placeholders::error, t, count));
    }
}

int main()
{ 
    boost::asio::io_service io;
    int count = 0;
    boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));

    t.async_wait(boost::bind(print, boost::asio::placeholders::error, &t, &count));

    io.run();
    std::cout << "Final count is " << count << std::endl;

    return 0;

}

它做了它应该做的事情:数到五。 可以帮助别人。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM