如何使boost / asio库重复计时器?

时间:2015-05-22 05:56:25

标签: c++ boost boost-asio boost-thread

以下是Boost库文档中给出的代码。

#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。 有可能吗?

1 个答案:

答案 0 :(得分:7)

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

#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 tutorials