#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
struct Timer {
template<typename F> void setTimeout(F func, uint32_t milliseconds);
template<typename F> void setInterval(F func, uint32_t milliseconds);
template<typename F> void setTimeoutSec(F func, uint32_t seconds);
template<typename F> void setIntervalSec(F func, uint32_t seconds);
void stop();
private: std::atomic<bool> alive{ true };
};
template<typename F> void Timer::setTimeout(F func, uint32_t milliseconds) {
alive = true; std::thread t([=]() {
std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
if (!alive.load()) return; func();
});
t.detach();
}
template<typename F> void Timer::setInterval(F func, uint32_t milliseconds) {
alive = true; std::thread t([=]() {
while (alive.load()) {
std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
if (!alive.load()) return; func();
}
});
t.detach();
}
template<typename F> void Timer::setTimeoutSec(F func, uint32_t seconds) {
alive = true; std::thread t([=]() {
std::this_thread::sleep_for(std::chrono::seconds(seconds));
if (!alive.load()) return; func();
});
t.detach();
}
template<typename F> void Timer::setIntervalSec(F func, uint32_t seconds) {
alive = true; std::thread t([=]() {
while (alive.load()) {
std::this_thread::sleep_for(std::chrono::seconds(seconds));
if (!alive.load()) return; func();
}
});
t.detach();
}
void Timer::stop() { alive = false; }
//#include "timer.h" 上面可以单独出来一个文件,这里只为方便演示
using namespace std;
int main() {
std::locale::global(std::locale(u8"en_US.UTF8"));//设置控制台打印
Timer t; int i = 0; bool run = true;//标记是否正运行
t.setTimeout([&t,&run]() {
cout << u8"经过6.18s" << endl;
t.stop(); run = false;
}, 6180);
t.setInterval([&i]() {
cout << u8"持续"<< ++i << u8"秒" << endl;
}, 1000);
cout << u8"定时器开始!" << endl;
while (run) this_thread::yield();//当前线程优先级滞后操作
//让当前线程始终在多线程的队尾,防止其他线程提前执行return 0;
return 0;
}
好了,这次又是本人在吃螃蟹。可以感受一下,c++的最简洁写法,欢迎留言讨论。
|