c++实现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;
  return 0;
}

好了,这次又是本人在吃螃蟹。可以感受一下,c++的最简洁写法,欢迎留言讨论。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值