In this tutorial we will modify the program from tutorial Timer.2 so that the timer fires once a second. This will show how to pass additional parameters to your handler function.

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

To implement a repeating timer using asio you need to change the timer's expiry time in your callback function, and to then start a new asynchronous wait. Obviously this means that the callback function will need to be able to access the timer object. To this end we add two new parameters to the print function:

  • A pointer to a timer object.
  • A counter so that we can stop the program when the timer fires for the sixth time.
void print(const boost::system::error_code& /*e*/,
boost::asio::deadline_timer* t, int* count)
{

As mentioned above, this tutorial program uses a counter to stop running when the timer fires for the sixth time. However you will observe that there is no explicit call to ask the io_service to stop. Recall that in tutorial Timer.2 we learnt that the boost::asio::io_service::run() function completes when there is no more "work" to do. By not starting a new asynchronous wait on the timer when count reaches 5, the io_service will run out of work and stop running.

  if (*count < 5)
{
std::cout << *count << "\n";
++(*count);

Next we move the expiry time for the timer along by one second from the previous expiry time. By calculating the new expiry time relative to the old, we can ensure that the timer does not drift away from the whole-second mark due to any delays in processing the handler.

    t->expires_at(t->expires_at() + boost::posix_time::seconds(1));

Then we start a new asynchronous wait on the timer. As you can see, the boost::bind() function is used to associate the extra parameters with your callback handler. The boost::asio::deadline_timer::async_wait() function expects a handler function (or function object) with the signature void(const boost::system::error_code&). Binding the additional parameters converts your print function into a function object that matches the signature correctly.

See the Boost.Bind documentation for more information on how to use boost::bind().

In this example, the boost::asio::placeholders::error argument to boost::bind() is a named placeholder for the error object passed to the handler. When initiating the asynchronous operation, and if using boost::bind(), you must specify only the arguments that match the handler's parameter list. In tutorial Timer.4 you will see that this placeholder may be elided if the parameter is not needed by the callback handler.

    t->async_wait(boost::bind(print,
boost::asio::placeholders::error, t, count));
}
} int main()
{
boost::asio::io_service io;

A new count variable is added so that we can stop the program when the timer fires for the sixth time.

  int count = 0;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));

As in Step 4, when making the call to boost::asio::deadline_timer::async_wait() from main we bind the additional parameters needed for the print function.

  t.async_wait(boost::bind(print,
boost::asio::placeholders::error, &t, &count)); io.run();

Finally, just to prove that the count variable was being used in the print handler function, we will print out its new value.

  std::cout << "Final count is " << count << "\n";

  return 0;
}

See the full source listing

Return to the tutorial index

Previous: Timer.2 - Using a timer asynchronously

Next: Timer.4 - Using a member function as a handler

Timer.3 - Binding arguments to a handler的更多相关文章

  1. Timer.4 - Using a member function as a handler

    In this tutorial we will see how to use a class member function as a callback handler. The program s ...

  2. boost::asio译文

        Christopher Kohlhoff Copyright © 2003-2012 Christopher M. Kohlhoff 以Boost1.0的软件授权进行发布(见附带的LICENS ...

  3. Boost.Asio技术文档

    Christopher Kohlhoff Copyright © 2003-2012 Christopher M. Kohlhoff 以Boost1.0的软件授权进行发布(见附带的LICENSE_1_ ...

  4. 【转】Timer还是Handler

    在我们Android开发过程中,经常需要执行一些短周期的定时任务,这时候有两个选择Timer或者Handler.然而个人认为:Handler在多个方面比Timer更为优秀,更推荐使用. 一.易用性 1 ...

  5. android Handler vs Timer

    Handler vs Timer 在我们Android开发过程中,经常需要执行一些短周期的定时任务,这时候有两个选择Timer或者Handler.然而个人认为: Handler 在多个方面比Timer ...

  6. 倒计时 总结 Timer Handler CountDownTimer RxJava MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  7. Handler vs Timer,究竟该用哪个?

    Handler vs Timer 在我们Android开发过程中,经常需要执行一些短周期的定时任务,这时候有两个选择Timer或者Handler.然而个人认为:Handler在多个方面比Timer更为 ...

  8. Handler使用总结(转)

    方法一:(java习惯,在android平台开发时这样是不行的,因为它违背了单线程模型) 刚刚开始接触android线程编程的时候,习惯好像java一样,试图用下面的代码解决问题 new Thread ...

  9. Handler的总结

    Handler的总结 我们创建的Service.Activity,Broadcast均是一个主线程处理,即UI线程, 但是进行耗时操作时,比如I/O读写的大文件,数据库操作及网络下载需要很长的时间,为 ...

随机推荐

  1. .NET基础拾遗(4)委托为何而生?

    生活中的例子: 你早上要吃包子作为早饭,那么你可能让你爸爸或者妈妈帮你做,那你就会调用 爸爸.要包子() 或妈妈.要包子() 返回包子对象. 但是如果你爸妈不在家的时候,你只能去街上买,问题是你根本不 ...

  2. [MVC4-基礎] 使用DataAnnotations+jQuery進行表單驗證

    我目前有以下表單,Select部分因為必須上一層有選擇下層才有資料,因此使用jQuery驗證問題類型是否有選擇就好,而問題描述要驗證是否為空,這裡採用MVC內建的DataAnnotations來驗證. ...

  3. 不指定order by时Sql的排序

    在sql中不指定Order by,排序是按照主键吗?答案是不一定.举个例子:   查询AttendanceEmpRank表,主键是AttendanceEmployeeRankId,而且是聚集索引   ...

  4. Tomcat6+nginx集群,达到负载均衡和session复制

    nginx+tomcat做web项目集群,达到负载均衡.故障转移.session复制功能. 1.nginx配置文件见上一篇“nginx配置文件(反向代理+集群+动静分离)” 2.tomcat集群,修改 ...

  5. Ztree中simpleData是怎么转换成标准ztree数组对象的

    今天遇到一个自己构造树的情况,树是动态的,预先不知道根节点,用的是easyUI中的tree,于是参考了下Ztree中的实现,恍然大悟,遂记之: transformTozTreeFormat: func ...

  6. UC浏览器 分享到朋友圈和微信好友

    用手机UC浏览器访问新浪微博,会注意到有这样的两个分享按钮: 在手机端浏览器里,点击分享按钮,就可以启动微信客户端并分享到微信.研究了下其源代码,存在这样的一个js:http://mjs.sinaim ...

  7. Array.prototype.sort()

    sort() 方法对数组的元素做原地的排序,并返回这个数组.默认按照字符串的Unicode码位点(code point)排序. 语法 arr.sort([compareFunction]) 参数 co ...

  8. [Leetcode] Longest Consecutive Sequence 略详细 (Java)

    题目参见这里 https://leetcode.com/problems/longest-consecutive-sequence/ 这个题目我感觉很难,看了半天别人写的答案,才明白个所以然.下面的代 ...

  9. JDBC框架

    一.元数据介绍 元数据指的是"数据库"."表"."列"的定义信息. 1.1.DataBaseMetaData元数据 Connection.g ...

  10. Java根据字节数据判断文件类型

    通常,在WEB系统中,上传文件时都需要做文件的类型校验,大致有如下几种方法: 1. 通过后缀名,如exe,jpg,bmp,rar,zip等等. 2. 通过读取文件,获取文件的Content-type来 ...