#include "CTimer.h"
CTimer::CTimer()
: m_quit(false)
, m_wake(false)
{
}
CTimer::~CTimer()
{
}
void CTimer::start(int second, TimeoutHandle handle)
{
if (m_timer.get() && m_timer->joinable()) {
return;
}
run(second, handle);
}
void CTimer::reset()
{
if (m_timer.get() && m_timer->joinable()) {
std::unique_lock<std::mutex> locker(m_mutex);
{
m_wake = true;
m_condition.notify_all();
}
}
}
void CTimer::stop()
{
if (m_timer.get() && m_timer->joinable()) {
m_quit = true;
reset();
m_timer->join();
m_timer.reset();
}
}
void CTimer::run(int second, TimeoutHandle handle)
{
m_timer.reset(new std::thread(
[this, second, handle]() {
m_quit = false;
while (!m_quit) {
std::unique_lock<std::mutex> locker(m_mutex);
{
m_wake = false;
bool bRet = m_condition.wait_for(locker, std::chrono::seconds(second), [this] { return m_wake; });
if (!bRet) {
if (handle) {
handle();
}
}
}
}
}
));
}