1 源码
//参数传入 Binding arguments to a handler
#include "stdafx.h"
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
//因为要开启一个重复的计时,所以需要把timer的指针也传进来
void print(const boost::system::error_code& /*e*/,
boost::asio::deadline_timer* t, int* count)
{
if (*count < 5)
{
std::cout << *count << std::endl;
++(*count);
t->expires_at(t->expires_at() + boost::posix_time::seconds(1)); //重新设定计时,这里加上了超时时间,以保证下次计时仍然是1s,不会因为程序执行的耗时,导致时间不准确。
t->async_wait(boost::bind(print,
boost::asio::placeholders::error, t, count));
}
}
int main()
{
boost::asio::io_service io;
int count = 0;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
t.async_wait(boost::bind(print,
boost::asio::placeholders::error, &t, &count));//传入参数count,参数传入的顺序与回调函数是一致的
io.run();
std::cout << "Final count is " << count << std::endl;
getchar(); //暂停程序。
return 0;
}
2 运行结果