[英]Make a Timer with boost::asio::deadline_timer
I want to make a Timer class with boost::asio::deadline_timer.我想用 boost::asio::deadline_timer 制作一个 Timer 类。 I looked into this: How do I make the boost/asio library repeat a timer?
我研究了这个: 如何让 boost/asio 库重复计时器?
class DeadlineTimer
{
boost::asio::io_service io;
std::function<void()> fun;
boost::asio::deadline_timer t;
void runTimer()
{
fun();
t.expires_at(t.expires_at() + boost::posix_time::seconds(2));
t.async_wait(boost::bind(&DeadlineTimer::runTimer, this));
}
public:
DeadlineTimer() :t(io, boost::posix_time::seconds(2)){}
void setFunction(std::function<void()> _f)
{
fun = _f;
}
void run()
{
io.run();
}
};
void test()
{
DeadlineTimer timer1;
auto f = []() {
cout << "hello world\n";
};
timer1.setFunction(f);
timer1.run();
}
It allows user to pass a self-defined timer function via timer1.setFunction(f);
它允许用户通过
timer1.setFunction(f);
传递一个自定义的定时器函数timer1.setFunction(f);
. . Then repeatedly run it (in every 2 second under current circumstance).
然后重复运行它(在当前情况下每2秒一次)。
But it doesn't work, no output at all.但它不起作用,根本没有输出。
After some trial-and-error, I've managed to update David Wyles' boost::asio::repeating_timer class to work with Boost >= 1.66 - this neatly encapsulates the functionality of a repeating timer.经过一些反复试验,我设法更新了 David Wyles 的 boost::asio::repeating_timer 类以使用 Boost >= 1.66 - 这巧妙地封装了重复计时器的功能。 Online at https://github.com/mikehaben69/boost , including demo source and makefile.
在线https://github.com/mikehaben69/boost ,包括演示源和生成文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.