boost.asio系列(一)——deadline_timer

时间:2023-03-09 06:24:19
boost.asio系列(一)——deadline_timer

一.构造函数

  一个deadline_timer只维护一个超时时间,一个deadline_timer不同时维护多个定时器。在构造deadline_timer时指定时间:

 basic_deadline_timer(boost::asio::io_service & io_service);

 basic_deadline_timer( boost::asio::io_service & io_service,
const time_type & expiry_time); basic_deadline_timer(boost::asio::io_service & io_service,
const duration_type & expiry_time);

二.同步定时器

  由于不涉及到异步,该函数和io_service没有什么关系。只是简单的sleep。

 boost::asio::io_service io;
boost::asio::deadline_timer t(io, boost::posix_time::seconds());
t.wait();

三.异步定时器

  由于涉及到异步,该函数需要io_service来运行run,进行调度。

 boost::asio::io_service io;
boost::asio::deadline_timer t(io, boost::posix_time::seconds());
t.async_wait(handler);

四.例子

 #include<boost/asio.hpp>
#include<boost/ref.hpp>
#include<iostream> using namespace std;
typedef function<void (const boost::system::error_code&)> timer_callback ; void print(const boost::system::error_code&)
{
cout << "async timer."<<endl;
} void bindPrint(const boost::system::error_code & err,boost::asio::deadline_timer &timer)
{
cout<<"bind loop async timer."<<endl;
timer.expires_at(timer.expires_at() + boost::posix_time::seconds());
timer.async_wait(std::bind(bindPrint, std::placeholders::_1, boost::ref(timer)));
} int main()
{
boost::asio::io_service io; //1.基本的同步定时器
boost::asio::deadline_timer timer1(io, boost::posix_time::seconds());
timer1.wait(); //2.基本的异步定时器
boost::asio::deadline_timer timer2(io, boost::posix_time::seconds());
timer2.async_wait(print); //3.使用lambda来生成回调函数
boost::asio::deadline_timer timer3(io, boost::posix_time::seconds());
timer_callback callback = [&](const boost::system::error_code& err)
{
cout<<"lambda loop async timer."<<endl;
timer3.expires_at(timer3.expires_at() + boost::posix_time::seconds());
timer3.async_wait(callback);
};
timer3.async_wait(callback); //4.使用bind来生成回调函数
boost::asio::deadline_timer timer4(io, boost::posix_time::seconds());
timer4.async_wait(std::bind(bindPrint, std::placeholders::_1, boost::ref(timer4))); io.run();
return ;
}

五.补充

1.deadline_timer的计时是在定义后,即timer构造函数完成后就开始,而不是调用wait()或者async_wati()后开始计时。

2.deadline_timer不能进行拷贝的,所以在bind中必须使用boost::ref进行包裹。