Reputation: 3253
I am using the from boost suggested solution for a timed callback which can be found here. I am using it to run the timed callback in parallel to other methods. But when I am executing a loop after setting the callback, the callback stops:
//this is the main cpp file
void print(const boost::system::error_code& /*e*/)
{
std::cout << "Hello, world!\n";
}
int main(int argc, char** argv)
{
boost::asio::io_service io;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
t.async_wait(print);
io.run();
....some part later I then call a function with while(){} loop inside....
eng.Loopfunction();
After Loopfunction() is called, the timed callback doesn't work anymore. Do you know how to overcome this problem?
Thanks.
Upvotes: 1
Views: 412
Reputation: 2057
the timed callback doesn't work anymore
Is it called only once?
According to the code:
io.run()
blocks the main threadprint
is called onceio.run()
unblocks the main threadeng.Loopfunction
is calledThat how it must work. Note that deadline_timer
is called only once. If you want timer to be called each second, you need to call deadline_timer::async_wait
at the end of print
like that:
boost::asio::io_service io;
deadline_timer t(io);
void print(const boost::system::error_code& /*e*/)
{
std::cout << "Hello, world!\n";
// call this function again in 1 second
t.expires_from_now( boost::posix_time::seconds(1) );
t.async_wait(print);
}
int main(int argc, char** argv)
{
t.expires_from_now( boost::posix_time::seconds(1) );
t.async_wait(print);
io.run();
Upvotes: 1