c – 如何使boost / asio库重复计时器?
作者:互联网
以下是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.
可能吗 ?
解决方法:
您可以通过在计时器处理程序中调用deadline_timer :: expires_from_now和deadline_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;
}
标签:boost-thread,c,boost,boost-asio 来源: https://codeday.me/bug/20191008/1874441.html