使用asio::steady_timer需先构造并传入io_context,再调用async_wait绑定void(std::error_code)签名的回调;必须确保io_context生命周期长于timer且有线程执行run(),否则回调不触发。
直接用 asio::steady_timer,它基于单调时钟,不会受系统时间调整影响,比 asio::system_timer 更适合做超时或延时任务。构造时传入 io_context,再调用 async_wait() 并绑定回调——此时不会阻塞线程,计时器在后台由 io_context::run() 驱动。
常见错误是忘记调用 run() 或只调用一次就退出,导致回调永不执行;或者重复构造 timer 但没重置,造成未定义行为。
io_context 生命周期长于 timer,且至少有一个线程在调用 run() 或 run_one()
void(std::error_code),std::error_code 非零表示取消或过期失败ec 为 asio::error::operation_aborted
#include#include int main() { boost::asio::io_context io; boost::asio::steady_timer t(io, std::chrono::seconds(2)); t.async_wait([](const boost::system::error_code& ec) { if (!ec) { std::cout << "Timer fired!\n"; } else if (ec == boost::asio::error::operation_aborted) { std::cout << "Timer was cancelled\n"; } }); io.run(); // 必须调用,否则无反应 }
调用 cancel() 是唯一标准方式,它会立即让 pending 的 async_wait 回调以 asio::error::operation_aborted 触发。注意:cancel 不会等待回调返回,也不保证回调已开始执行——所以回调里访问外部对象前,必须确认其是否还有效。
典型陷阱是 timer 对象被销毁后,回调仍试图访问捕获的局部变量或 this 指针,引发 UAF(use-after-free)。
std::shared_ptr 管理 timer 和关联数据,回调中用 weak_ptr.lock() 判活shared_ptr 或显式传参cancel() 可多次调用,无副作用;但不能在另一个线程里直接调用,除非 io_context 支持多线程或已 post 到对应 strand完全不会。asio 的 timer 是独立对象,每个都维护自己的到期时间和回调队列,底层由 io_context 统一调度。只要不共享同一 timer 实例,它们之间无耦合。
但要注意资源竞争点:所有回调都在 io_context 的调用线程中执行(默认单线程),若某个回调耗时过长,会阻塞后续 timer 回调和其它异步操作的派发。
strand 分组隔离,或把重负载逻辑 offload 到线程池steady_timer 内部用的是最小堆,插入/取消均摊 O(log n),性能可接受;但频繁创建销毁建议复用 timer 实例(调用 expires_after() + async_wait())sleep 或 busy-wait 替代 timer,那会破坏非阻塞模型最常见原因是 io_context::run() 提前退出了。asio 的 run() 在没有 pending 操作时会立即返回,而 timer 的等待属于 pending 操作——但如果 timer 构造后没来得及进入队列、或被 cancel 了,run() 就认为“无事可做”,直接结束。
另一个隐蔽原因是 timer 对象生命周期结束早于 run(),比如它是个局部变量,在 main() 结束时析构,触发内部 cancel,但此时 io_context 可能还没开始调度。
std::cout 看是否有 pending 操作
run() 过程,推荐堆上分配或作为类成员持有io_context::work(C++20 后建议用 executor_work_guard)防止 run() 过早退出