...one of the most highly regarded and expertly designed C++ library projects in the world.
— Herb Sutter and Andrei Alexandrescu, C++ 编码标准
基于高分辨率时钟的定时器的类型定义。
typedef basic_waitable_timer< chrono::high_resolution_clock > high_resolution_timer;
名称 |
描述 |
---|---|
将定时器类型重新绑定到另一个执行器。 |
|
时钟类型。 |
|
时钟的持续时间类型。 |
|
与对象关联的执行器的类型。 |
|
时钟的时间点类型。 |
|
等待特性类型。 |
名称 |
描述 |
---|---|
启动定时器的异步等待。 |
|
basic_waitable_timer [构造函数] |
构造函数。 |
取消任何正在等待定时器的异步操作。 |
|
取消一个正在等待定时器的异步操作。 |
|
设置定时器的到期时间,相对于现在。 |
|
设置定时器的到期时间为绝对时间。 |
|
获取定时器的到期时间,为绝对时间。 |
|
获取与对象关联的执行器。 |
|
从另一个 basic_waitable_timer 移动赋值一个。 |
|
对定时器执行阻塞等待。 |
|
~basic_waitable_timer [析构函数] |
销毁定时器。 |
The basic_waitable_timer
类模板提供了对定时器执行阻塞或异步等待以使其过期的能力。
可等待定时器始终处于两种状态之一:“已过期”或“未过期”。如果在已过期的定时器上调用 wait()
或 async_wait()
函数,则等待操作将立即完成。
大多数应用程序将使用 steady_timer
, system_timer
或 high_resolution_timer
类型定义之一。
此可等待定时器功能用于 C++11 标准库的 <chrono>
功能,或 Boost.Chrono 库。
独立 对象: 安全。
共享 对象: 不安全。
执行阻塞等待 (C++11)
// Construct a timer without setting an expiry time. boost::asio::steady_timer timer(my_context); // Set an expiry time relative to now. timer.expires_after(std::chrono::seconds(5)); // Wait for the timer to expire. timer.wait();
执行异步等待 (C++11)
void handler(const boost::system::error_code& error) { if (!error) { // Timer expired. } } ... // Construct a timer with an absolute expiry time. boost::asio::steady_timer timer(my_context, std::chrono::steady_clock::now() + std::chrono::seconds(60)); // Start an asynchronous wait. timer.async_wait(handler);
在存在待处理的异步等待时更改定时器的到期时间会导致这些等待操作被取消。为了确保与定时器关联的操作仅执行一次,请使用如下方法:used
void on_some_event() { if (my_timer.expires_after(seconds(5)) > 0) { // We managed to cancel the timer. Start new asynchronous wait. my_timer.async_wait(on_timeout); } else { // Too late, timer has already expired! } } void on_timeout(const boost::system::error_code& e) { if (e != boost::asio::error::operation_aborted) { // Timer was not cancelled, take necessary action. } }
boost::asio::basic_waitable_timer::expires_after()
函数会取消任何待处理的异步等待,并返回已取消的异步等待的数量。如果它返回 0,则您为时已晚,等待处理程序已执行或即将执行。如果它返回 1,则等待处理程序已成功取消。boost::system::error_code
包含值 boost::asio::error::operation_aborted
。如果可用,此类型定义使用 C++11 <chrono>
标准库工具。否则,它可能使用 Boost.Chrono 库。要显式使用 Boost.Chrono,请直接使用 basic_waitable_timer
模板
typedef basic_waitable_timer<boost::chrono::high_resolution_clock> timer;
头文件: boost/asio/high_resolution_timer.hpp
便利头文件: boost/asio.hpp