Reputation: 3346
I want to make a Timer class with boost::asio::deadline_timer. I looked into this: How do I make the boost/asio library repeat a timer?
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);
. Then repeatedly run it (in every 2 second under current circumstance).
But it doesn't work, no output at all.
Upvotes: 0
Views: 356
Reputation: 147
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. Online at https://github.com/mikehaben69/boost, including demo source and makefile.
Upvotes: 1