-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTimer.hpp
47 lines (42 loc) · 970 Bytes
/
Timer.hpp
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
#pragma once
#include <functional>
#include <thread>
#include <chrono>
#ifdef _DEBUG
#define INLINE inline
#else
#define INLINE __forceinline
#endif
class Timer {
public:
Timer(int interval, std::function<void()> task)
: m_interval(interval), m_task(task) {};
virtual ~Timer() {};
void Start()
{
if (!m_isRunning) {
m_isRunning = true;
m_thread = std::thread(&Timer::loop, this);
}
}
void Stop()
{
if (m_isRunning) {
m_isRunning = false;
TerminateThread(m_thread.native_handle(), 0);
if (m_thread.joinable())
m_thread.join();
}
}
private:
int m_interval;
std::function<void()> m_task;
std::thread m_thread;
bool m_isRunning=false;
void loop() {
while (m_isRunning) {
m_task();
std::this_thread::sleep_for(std::chrono::milliseconds(m_interval));
}
}
};