boost库之asio库, 定时器

来源:互联网 发布:怎么在淘宝卖游戏装备 编辑:程序博客网 时间:2024/04/30 09:03

一、同步定时器

1.1 代码

#include <iostream>using namespace std;#include <boost/asio.hpp>#include <boost/date_time/posix_time/posix_time.hpp>using namespace boost;using namespace boost::asio;int main(int argc, char*argv[]){io_service ios;deadline_timer t(ios, posix_time::seconds(3));cout<<t.expires_from_now()<<", "<<t.expires_at()<<endl;t.wait();cout<<"hello"<<endl;return 0;}

1.2 结果



二、异步定时器

2.1 代码

#include <iostream>using namespace std;#include <boost/asio.hpp>#include <boost/date_time/posix_time/posix_time.hpp>using namespace boost;using namespace boost::asio;void print(const system::error_code& e){cout<<"async hello."<<endl;}int main(int argc, char*argv[]){io_service ios;deadline_timer t(ios, posix_time::seconds(3));t.async_wait(print);ios.run();return 0;}

2.2 结果



三、异步定时器使用bind

3.1 代码

#include <iostream>using namespace std;#include <boost/asio.hpp>#include <boost/date_time/posix_time/posix_time.hpp>#include <boost/bind.hpp>using namespace boost;using namespace boost::asio;class a_timer{public:template<typename F>a_timer(io_service &ios, int c, F func) : count(0), max_count(c), t(ios, posix_time::millisec(500)), f(func){t.async_wait(boost::bind(&a_timer::func_proc, this, boost::asio::placeholders::error));}void func_proc(const system::error_code& e){if(count >= max_count)return;++count;f();t.expires_at(t.expires_at() + posix_time::millisec(500));t.async_wait(boost::bind(&a_timer::func_proc, this, boost::asio::placeholders::error));}private:int count, max_count;deadline_timer t;boost::function<void ()> f;};void print1(){cout<<"timer 1."<<endl;}void print2(){cout<<"timer 2."<<endl;}int main(int argc, char*argv[]){io_service ios;a_timer a1(ios, 5, print1);a_timer a2(ios, 3, print2);ios.run();return 0;}

3.2 结果




参考资料:

      《Boost程序库完全开发指南》    12.2.2 节和12.2.3节    (P507)