Boost C++ 库

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ 编码标准

PrevUpHomeNext

high_resolution_timer

基于高分辨率时钟的定时器的类型定义。

typedef basic_waitable_timer< chrono::high_resolution_clock > high_resolution_timer;
类型

名称

描述

rebind_executor

将定时器类型重新绑定到另一个执行器。

clock_type

时钟类型。

duration

时钟的持续时间类型。

executor_type

与对象关联的执行器的类型。

time_point

时钟的时间点类型。

traits_type

等待特性类型。

成员函数

名称

描述

async_wait

启动定时器的异步等待。

basic_waitable_timer [构造函数]

构造函数。

构造函数,用于将特定到期时间设置为绝对时间。

构造函数,用于将特定到期时间设置为相对于现在的时间。

从另一个 basic_waitable_timer 移动构造一个。

cancel

取消任何正在等待定时器的异步操作。

cancel_one

取消一个正在等待定时器的异步操作。

expires_after

设置定时器的到期时间,相对于现在。

expires_at

设置定时器的到期时间为绝对时间。

expiry

获取定时器的到期时间,为绝对时间。

get_executor

获取与对象关联的执行器。

operator=

从另一个 basic_waitable_timer 移动赋值一个。

wait

对定时器执行阻塞等待。

~basic_waitable_timer [析构函数]

销毁定时器。

The basic_waitable_timer 类模板提供了对定时器执行阻塞或异步等待以使其过期的能力。

可等待定时器始终处于两种状态之一:“已过期”或“未过期”。如果在已过期的定时器上调用 wait()async_wait() 函数,则等待操作将立即完成。

大多数应用程序将使用 steady_timer, system_timerhigh_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.
  }
}

如果可用,此类型定义使用 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


PrevUpHomeNext