我正在使用 from boost 建议的解决方案进行定时回调,可以在这里找到。我正在使用它与其他方法并行运行定时回调。但是当我在设置回调后执行循环时,回调停止:
//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();
调用 Loopfunction() 后,定时回调不再起作用。你知道如何克服这个问题吗?
谢谢。
定时回调不再起作用
只叫一次吗?
根据代码:
-
io.run()
阻塞主线程 -
print
被调用一次 -
io.run()
解锁主线程 -
eng.Loopfunction
被称为
它必须如何工作。请注意,deadline_timer
只调用一次。如果你想每秒调用计时器,你需要在print
结束时调用deadline_timer::async_wait
,如下所示:
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();