1 // copied from muduo/net/tests/TimerQueue_unittest.cc 2 3 #include "Channel.h" 4 #include "EventLoop.h" 5 6 #include <boost/bind.hpp> 7 8 #include <stdio.h> 9 10 int cnt = 0; 11 muduo::EventLoop* g_loop; 12 13 void printTid() 14 { 15 printf("pid = %d, tid = %d\n", getpid(), muduo::CurrentThread::tid()); 16 printf("now %s\n", muduo::Timestamp::now().toString().c_str()); 17 } 18 19 void print(const char* msg) 20 { 21 printf("msg %s %s\n", muduo::Timestamp::now().toString().c_str(), msg); 22 if (++cnt == 20) 23 { 24 g_loop->quit(); 25 } 26 } 27 28+muduo::TimerId toCancel; 29+void cancelSelf() 30+{ 31+ print("cancelSelf()"); 32+ g_loop->cancel(toCancel); 33+} 34+ 35 int main() 36 { 37 printTid(); 38 muduo::EventLoop loop; 39 g_loop = &loop; 40 41 print("main"); 42 loop.runAfter(1, boost::bind(print, "once1")); 43 loop.runAfter(1.5, boost::bind(print, "once1.5")); 44 loop.runAfter(2.5, boost::bind(print, "once2.5")); 45 loop.runAfter(3.5, boost::bind(print, "once3.5")); 46- loop.runEvery(2, boost::bind(print, "every2")); 47+ muduo::TimerId t = loop.runEvery(2, boost::bind(print, "every2")); 48 loop.runEvery(3, boost::bind(print, "every3")); 49+ loop.runAfter(10, boost::bind(&muduo::EventLoop::cancel, &loop, t)); 50+ toCancel = loop.runEvery(5, cancelSelf); 51 52 loop.loop(); 53 print("main loop exits"); 54 sleep(1); 55 } 56