#include "TTimer.h"#include <QDebug>TTimer::TTimer(size_t interval, bool isRepeat): _expired(true), _try_to_expire(false),m_interval(interval),m_isRepeat(isRepeat){}TTimer::~TTimer(){stop();}void TTimer::start(std::function<void()> task){if (m_isRepeat) {// is started, do not start againif (_expired == false)return;// start async timer, launch thread and wait in that thread_expired = false;std::thread([this, task]() {while (!_try_to_expire){// sleep every interval and do the task again and again until times upstd::this_thread::sleep_for(std::chrono::milliseconds(m_interval));task();}{// timer be stopped, update the condition variable expired and wake main threadstd::lock_guard<std::mutex> locker(_mutex);_expired = true;_expired_cond.notify_one();}}).detach();} else {std::thread([this, task]() {std::this_thread::sleep_for(std::chrono::milliseconds(m_interval));task();this->_expired.store(true);}).detach();}}void TTimer::stop(){// do not stop againif (_expired)return;if (_try_to_expire)return;// wait until timer_try_to_expire = true; // change this bool value to make timer while loop stop{std::unique_lock<std::mutex> locker(_mutex);_expired_cond.wait(locker, [this] {return _expired == true; });// reset the timerif (_expired == true)_try_to_expire = false;}}bool TTimer::isExpired(){return _expired;}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。