gpt4 book ai didi

c++ - 如何让 boost/asio 库重复一个计时器?

转载 作者:太空狗 更新时间:2023-10-29 20:11:54 25 4
gpt4 key购买 nike

这是 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_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 .

关于c++ - 如何让 boost/asio 库重复一个计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30389323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com