-
Notifications
You must be signed in to change notification settings - Fork 37
/
Timer.h
56 lines (46 loc) · 1.48 KB
/
Timer.h
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
#pragma once
#include <windows.h>
#include <functional>
#include <map>
class Timer {
typedef std::function<void()> Callback;
public:
static void SingleShot(unsigned int milliseconds, Callback func) {
UINT_PTR taskId = SetTimer(NULL, NULL, milliseconds, TimerProc);
m_timers[taskId] = { func, true };
}
static UINT_PTR Schedule(unsigned int milliseconds, Callback func) {
UINT_PTR taskId = SetTimer(NULL, NULL, milliseconds, TimerProc);
m_timers[taskId] = { func, false };
return taskId;
}
static void Cancel(UINT_PTR taskId) {
KillTimer(NULL, taskId);
m_timers.erase(taskId);
}
static void StopAll() {
for (auto &x : m_timers) {
KillTimer(NULL, x.first);
}
m_timers.clear();
}
private:
static void CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) {
if (uMsg == WM_TIMER) {
if (m_timers.find(idEvent) != m_timers.end()) {
if (m_timers[idEvent].IsSingleShot) {
KillTimer(hwnd, idEvent);
}
m_timers[idEvent].Callback();
if (m_timers[idEvent].IsSingleShot) {
m_timers.erase(idEvent);
}
}
}
}
struct TimerInfo {
Callback Callback;
bool IsSingleShot;
};
static std::map<UINT_PTR, TimerInfo> m_timers;
};