boost中asio的deadline_timer示例

http://outofmemory.cn/code-snippet/1089/boost-asio-deadline-timer-shili

  1. deadline_timer的同步与异步调用
  2. deadline_timer异步调用时必须定义回调函数或类3 使用boost::bind绑定回调函数
【boost中asio的deadline_timer示例】[C/C++]代码
/* * g++ -o timer asio_timer.cpp -lboost_system -lboost_date_time -lboost_thread */#include #include #include #include class printer { public: printer(boost::asio::io_service& io): timer_(io, boost::posix_time::seconds(1)), count_(0) { timer_.async_wait(boost::bind(&printer::print, this)); }~printer() { std::cout << "Final count is " << count_ << "" ; }void print() { if (count_ < 5) { std::cout << "print: " << "hello world times: " << count_ << std::endl; ++(count_); timer_.expires_at(timer_.expires_at() + boost::posix_time::seconds(1)); timer_.async_wait(boost::bind(&printer::print, this)); } }private: boost::asio::deadline_timer timer_; int count_; }; int main() { struct tm *myTm; char myDate[21]; int count = 0; time_t myTime = time(NULL); strftime(myDate, 21, "%Y-%m-%d %H:%M:%S", localtime(&myTime)); std::cout << myDate << std::endl; boost::asio::io_service io; printer p(io); io.run(); myTime = time(NULL); strftime(myDate, 21, "%Y-%m-%d %H:%M:%S", localtime(&myTime)); std::cout << myDate << std::endl; return 0; }

    推荐阅读