-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer.cpp
More file actions
88 lines (75 loc) · 1.61 KB
/
timer.cpp
File metadata and controls
88 lines (75 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/******************************************************************************
* File Name: timer.cpp
* Description:
* Notes:
* Author: Aseem Tiwari
* Date: 10/02/2021
******************************************************************************/
#include <chrono>
Timer::Timer(uint64_t timeMs, const std::function<void()>& callback, bool autoReset)
{
m_TimeInterval = timeMs;
m_AutoReset = autoReset;
m_Callback = std::cref(callback);
}
Timer::~Timer()
{
this->Dispose();
}
void Timer::TimerThreadFunc()
{
do
{
if (!m_Active.load())
{
return;
}
std::unique_lock<std::mutex> lock(m_MutexForCV);
if(m_CondVar.wait_for(lock, std::chrono::milliseconds(m_TimeInterval))
== std::cv_status::timeout && m_Active)
{
m_Callback();
}
else
{
return;
}
}while(m_AutoReset);
}
void Timer::Start()
{
if (!m_Callback)
{
return;
}
if (!m_TimerThread.joinable())
{
{
m_Active = true;
}
m_TimerThread = std::thread(&Timer::TimerThreadFunc, this);
m_TimerThread.detach();
}
}
void Timer::Restart(uint64_t timeMs)
{
if (timeMs != 0UL)
{
m_TimeInterval = timeMs;
}
this->Start();
}
void Timer::Stop()
{
{
std::lock_guard<std::mutex> lg(m_MutexForCV);
m_Active = false;
}
m_CondVar.notify_one();
}
void Timer::Dispose()
{
this->Stop();
m_TimeInterval = 0UL;
m_Callback = nullptr;
}