// ... 32: };
runAt 在指定的时间调用 TimerCallback
runAfter 等一段时间调用 TimerCallback
runEvery 以固定的间隔反复调用 TimerCallback
cancel 取消 timer,目前未实现
回调函数在 EventLoop 对象所在的线程发生,与 onMessage() onConnection() 等网络事件函数在同一个线程。
Muduo 的 TimerQueue 采用了最简单的实现(链表)来管理定时器,它的效率比不上常见的 binary heap 的做法,如果程序中大量(10 个以上)使用重复触发的定时器,或许值得考虑改用更高级的实现。我目前还没有在一个程序里用过这么多定时器,暂时也不打算优化 TimerQueue。
Boost.Asio Timer 示例
Boost.Asio 教程里以 Timer 和 Daytime 为例介绍 asio 的基本使用,daytime 已经在前文“示例一”中介绍过,这里着重谈谈 Timer。Asio 有 5 个 Timer 示例,muduo 把其中四个重新实现了一遍,并扩充了第 5 个示例。
阻塞式的定时,muduo 不支持这种用法,无代码。
非阻塞定时,见 examples/asio/tutorial/timer2
在 TimerCallback 里传递参数,见 examples/asio/tutorial/timer3
以成员函数为 TimerCallback,见 examples/asio/tutorial/timer4
在多线程中回调,用 mutex 保护共享变量,见 examples/asio/tutorial/timer5
在多线程中回调,缩小临界区,把不需要互斥执行的代码移出来,见 examples/asio/tutorial/timer6
为节省篇幅,这里只列出 timer4:
1: #include 2: 3: #include 4: #include 5: #include 6: 7: class Printer : boost::noncopyable 8: { 9: public: 10: Printer(muduo::net::EventLoop* loop) 11: : loop_(loop), 12: count_(0) 13: { 14: loop_->runAfter(1, boost::bind(&Printer::print, this)); 15: } 16: 17: ~Printer() 18: { 19: std::cout << "Final count is " << count_ << " "; 20: } 21: 22: void print() 23: { 24: if (count_ < 5) 25: { 26: std::cout << count_ << " "; 27: ++count_; 28: 29: loop_->runAfter(1, boost::bind(&Printer::print, this)); 30: } 31: else 32: { 33: &n