如何使boost/asio库重复计时? [英] How do I make the boost/asio library repeat a timer?

查看:102
本文介绍了如何使boost/asio库重复计时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Boost库文档中给出的代码.

Here is the Code given on the Boost library documentation.

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

void print(const boost::system::error_code& /*e*/)
{
  std::cout << "Hello, world!\n";
}

int main()
{
  boost::asio::io_service io;

  boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));
  t.async_wait(print);

  io.run();

  return 0;
}

现在,当我运行上述程序时,它将等待5秒钟,然后打印Hello World并停止. 我希望该程序每5秒继续打印一次Hello World. 有可能吗?

Now when I run the above program it just waits for 5 seconds and then prints Hello World and stop. I want this program to keep printing Hello World every 5 seconds. Is it possible ?

推荐答案

您可以通过在计时器处理程序中调用deadline_timer::expires_from_nowdeadline_timer::async_wait来执行此操作,这将在最后一个计时器到期时添加一个计时器.例如:

You can do this by calling deadline_timer::expires_from_now and deadline_timer::async_wait in your timer handler, this will add a timer once last one expires. for example:

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

void print(const boost::system::error_code& /*e*/,
    boost::asio::deadline_timer* t, int* count)
{
  if (*count < 5)
  {
    std::cout << *count << std::endl;
    ++(*count);

    t->expires_at(t->expires_at() + boost::posix_time::seconds(5));
    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(5));
  t.async_wait(boost::bind(print,
        boost::asio::placeholders::error, &t, &count));

  io.run();

  std::cout << "Final count is " << count << std::endl;

  return 0;
}

代码来自 Boosts Asio教程.

这篇关于如何使boost/asio库重复计时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆