首先,要理解一下定时器。
定时器想做做的事情是在固定的时刻去做某件事情。
那么定时器要有几种功能
创建一个定时器,去让在固定时刻去做某种事情
停止这个定时器,当满足某种条件时,不用定时器的任务继续跑了,停止这个定时器的运行。
删除这个定时器,当某种情况满足的时候不需要这个定时器的功能了,结束此定时器。
在git hab上有一个专用的c++定时器
https://github.com/eglimi/cpptime
其中定时器的使用有oneshot和周期性的
A one shot timer.
using namespace std::chrono;
CppTime::Timer t;
t.add(seconds(2), { std::cout << “yes\n”; });
std::this_thread::sleep_for(seconds(3));
A periodic timer that is first executed after 2 seconds, and after this every second. The timeout event is then removed after 10 seconds. When a timeout event is removed, its attached handler is also freed to clean-up any attached resources.
using namespace std::chrono;
CppTime::Timer t;
auto id = t.add(seconds(2), { std::cout << “yes\n”; }, seconds(1));
std::this_thread::sleep_for(seconds(10));