1 // 类似QTimer的定时器 2 class Timer 3 { 4 typedef void(* handler)(); 5 public: 6 Timer() 7 : m_millseconds(1000) 8 , m_timer(m_service, boost::posix_time::milliseconds(0)) 9 , m_handler(NULL) 10 , m_tick(6) 11 {} 12 13 /** 14 * @brief start 启动定时器 15 * @param time 定时间隔,毫秒为单位 16 */ 17 void start(int time = 1000) 18 { 19 m_millseconds = time; 20 update(); 21 22 boost::system::error_code error; 23 m_service.run(error); 24 } 25 26 /** 27 * @brief stop 停止定时器 28 */ 29 void stop() 30 { 31 m_timer.cancel(); 32 m_service.stop(); 33 } 34 35 /** 36 * @brief setHandle 设置句柄 37 * @param handle 定时器响应时,执行的句柄 38 */ 39 void setHandle(const handler handle) 40 { 41 m_handler = handle; 42 } 43 44 /** 45 * @brief setTicker 设置定时次数 46 * @param tick 定时次数 47 */ 48 void setTicker(int tick) 49 { 50 m_tick = tick; 51 } 52 53 private: 54 /** 55 * @brief time_handle 定时器响应函数 56 */ 57 void time_handle() 58 { 59 --m_tick; 60 if (m_tick <= 0) 61 { 62 stop(); 63 return; 64 } 65 66 if (m_handler != NULL) 67 { 68 m_handler(); 69 } 70 71 update(); 72 } 73 74 /** 75 * @brief update 更新定时器,实现重复响应效果 76 */ 77 void update() 78 { 79 using namespace boost::posix_time; 80 m_timer.expires_at(m_timer.expires_at() + milliseconds(m_millseconds)); 81 m_timer.async_wait(boost::bind(&Timer::time_handle, this)); 82 } 83 84 private: 85 int m_millseconds; 86 boost::asio::io_service m_service; 87 boost::asio::deadline_timer m_timer; 88 handler m_handler; 89 int m_tick; 90 };
依赖的头文件:
1 #include <boost/asio/deadline_timer.hpp> 2 #include <boost/system/system_error.hpp> 3 #include <boost/asio/io_service.hpp> 4 #include <boost/date_time/posix_time/posix_time.hpp>
依赖的boost库:
1. system
2. date_time
测试:
1 void print() 2 { 3 cout << "hello timer" << endl; 4 } 5 6 int main() 7 { 8 Timer t; 9 t.setHandle(&print); 10 t.start(); 11 12 return 0; 13 }