我想要一个非常简单的周期性定时器,每50ms调用一次我的代码。 我可以创build一个睡眠时间为50ms的线程(但是这很痛苦)…我可以开始研究Linux API来制作计时器(但它不是可移植的)…
我想使用提升..我只是不知道这是可能的。 增强提供这个function吗?
Boosts Asio教程的第二个例子解释了它。
你可以在这里找到它。
之后, 检查第三个例子 ,看看如何用定期的时间间隔再次调用它
一个非常简单,功能全面的例子:
#include <iostream> #include <boost/asio.hpp> boost::asio::io_service io_service; boost::posix_time::seconds interval(1); // 1 second boost::asio::deadline_timer timer(io_service, interval); void tick(const boost::system::error_code& /*e*/) { std::cout << "tick" << std::endl; // Reschedule the timer for 1 second in the future: timer.expires_at(timer.expires_at() + interval); // Posts the timer event timer.async_wait(tick); } int main(void) { // Schedule the timer for the first time: timer.async_wait(tick); // Enter IO loop. The timer will fire for the first time 1 second from now: io_service.run(); return 0; }
请注意,调用expires_at()
设置新的到期时间非常重要,否则计时器将立即触发,因为它的当前到期时间已到期。