boost中asio的deadline_timer示例

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

  1. deadline_timer的同步与异步调用
  2. deadline_timer异步调用时必须定义回调函数或类3 使用boost::bind绑定回调函数

[C/C++]代码

/*
 * g++ -o timer asio_timer.cpp -lboost_system -lboost_date_time -lboost_thread
 */

#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值