C++ 实现前端计时器

308 阅读1分钟

本文已参与「新人创作礼」活动.一起开启掘金创作之路。

其实c++,写计时器,我有过一段研究了,但是我发现许多代码呢写的都很乱。于是我突破,突进,突击c++底层,瞬间写了一个高大上的计时器,就是js中的计时器。在js计时器基础之上,我又加入了setTimeoutSec和setIntervelSec方法,也就是按照秒而不是原来的毫秒来算时间。调用方式和demo就在下面,几乎就是js的计时器。

#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;//如果没有上面那一行,程序就直接结束了
}