1
我已閱讀了許多關於此的帖子,但沒有找到這個問題的答案。 我想製作一個計時器類,它在後臺工作,並在完成時做一些事情。甚至我想要立即調用多個異步計數器。C++非阻塞異步計時器
我發現這個類,而我正在尋找它,似乎工作,但不是在background.How我可以轉換它做我想要的?
Timer.h:
#ifndef TIMER_H
#define TIMER_H
#include <thread>
#include <chrono>
class Timer
{
public:
typedef std::chrono::milliseconds Interval;
typedef std::function<void(void)> Timeout;
Timer(const Timeout &timeout);
Timer(const Timeout &timeout,
const Interval &interval,
bool singleShot = true);
void start(bool multiThread = false);
void stop();
bool running() const;
void setSingleShot(bool singleShot);
bool isSingleShot() const;
void setInterval(const Interval &interval);
const Interval &interval() const;
void setTimeout(const Timeout &timeout);
const Timeout &timeout() const;
private:
std::thread _thread;
bool _running = false;
bool _isSingleShot = true;
Interval _interval = Interval(0);
Timeout _timeout = nullptr;
void _temporize();
void _sleepThenTimeout();
};
#endif // TIMER_H
enter code here
Timer.cpp:
#include "Timer.h"
Timer::Timer(const Timeout &timeout)
: _timeout(timeout)
{
}
Timer::Timer(const Timer::Timeout &timeout,
const Timer::Interval &interval,
bool singleShot)
: _isSingleShot(singleShot),
_interval(interval),
_timeout(timeout)
{
}
void Timer::start(bool multiThread)
{
if (this->running() == true)
return;
_running = true;
if (multiThread == true) {
_thread = std::thread(
&Timer::_temporize, this);
}
else{
this->_temporize();
}
}
void Timer::stop()
{
_running = false;
_thread.join();
}
bool Timer::running() const
{
return _running;
}
void Timer::setSingleShot(bool singleShot)
{
if (this->running() == true)
return;
_isSingleShot = singleShot;
}
bool Timer::isSingleShot() const
{
return _isSingleShot;
}
void Timer::setInterval(const Timer::Interval &interval)
{
if (this->running() == true)
return;
_interval = interval;
}
const Timer::Interval &Timer::interval() const
{
return _interval;
}
void Timer::setTimeout(const Timeout &timeout)
{
if (this->running() == true)
return;
_timeout = timeout;
}
const Timer::Timeout &Timer::timeout() const
{
return _timeout;
}
void Timer::_temporize()
{
if (_isSingleShot == true) {
this->_sleepThenTimeout();
}
else {
while (this->running() == true) {
this->_sleepThenTimeout();
}
}
}
void Timer::_sleepThenTimeout()
{
std::this_thread::sleep_for(_interval);
if (this->running() == true)
this->timeout()();
}
您是否未在start方法中使用multithread參數來指示您希望它作爲單獨的線程運行? –
「背景」是什麼意思? – immibis
@immibis我認爲它是異步的意思。 –