#include <iostream>
#include <functional>
#include "boost/thread.hpp"
// 定时器回调函数
using TimerCallBack = std::function<void(void)>;
class CTimer {
public:
CTimer(TimerCallBack callback, int interval)
: time_callback_(callback)
, interval_(interval){
std::cout << "create timer" << std::endl;
}
bool start(){
std::cout << "start timer" << std::endl;
exec_ = true;
thread_ = boost::thread(boost::bind(&CTimer::exec, this));
return true;
}
void stop(){
std::cout << "stop timer" << std::endl;
exec_ = false;
if (thread_.joinable()){
condition_.notify_all();
thread_.join();
}
return;
}
private:
void exec(){
std::cout << "exec begin..." << std::endl;
boost::unique_lock<boost::mutex> locker(mutex_);
while (exec_){
// 此处建议用boost,std在linux下,如果系统时间经常变化,可能会导致wait卡死!!!
condition_.wait_for(locker, boost::chrono::milliseconds(interval_), [&]() {return !exec_; });
if (nullptr != time_callback_) {
static int call_count = 0;
std::cout << "callback call, count: " << ++call_count <<std::endl;
time_callback_();
}
}
std::cout << "exec end" << std::endl;
}
private:
bool exec_ = false;
int interval_ = 500; // 定时器间隔,单位毫秒
TimerCallBack time_callback_ = nullptr;
boost::thread thread_;
boost::mutex mutex_;
boost::condition_variable condition_;
};
void OnTimer(){
static int call_count = 0;
std::cout << "OnTimer call, count: " << ++call_count << std::endl;
}
int main()
{
CTimer timer(OnTimer, 500);
timer.start();
boost::this_thread::sleep(boost::chrono::seconds(6));
timer.stop();
}
08-10
3万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-01
5220
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-26
1822
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-26
1040
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交