-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathdeadline_timer.hpp
103 lines (86 loc) · 2.68 KB
/
deadline_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
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#ifndef DEADLINE_TIMER_HPP
#define DEADLINE_TIMER_HPP
#include "logging.hpp"
#include <iostream>
#include <thread>
#include <chrono>
#include <memory>
#include <functional>
#include <atomic>
/**
* @class DeadlineTimer
* @author Michael Griffin
* @date 17/02/2018
* @file deadline_timer.hpp
* @brief Timer class for Wait and AsyncWait.
*/
class DeadlineTimer
{
public:
explicit DeadlineTimer()
: m_log(Logging::getInstance())
, m_expires_from_now(0)
, m_num_instances (0)
{
}
~DeadlineTimer()
{
m_log.write<Logging::DEBUG_LOG>("~DeadlineTimer()");
}
typedef std::function<void(int)> StdFuncationCallBack;
Logging &m_log;
int m_expires_from_now;
std::atomic_int m_num_instances;
/**
* @brief Sets the waiting period for the timer.
* @param time
*/
void setWaitInMilliseconds(int time)
{
m_expires_from_now = time;
}
/**
* @brief Async Non-Block Wait (MilliSeconds) with Callback
* @param callback_method
*/
template <typename Callback>
void asyncWait(const Callback &callback_method)
{
// Values Passed to the Thread that don't change.
int i = m_expires_from_now;
int c = m_num_instances +1;
// Add to container to keep in an active scope
std::thread time_thread([i, c, callback_method, this]()
{
m_num_instances += 1;
std::this_thread::sleep_for(std::chrono::milliseconds(i));
StdFuncationCallBack fun_callback(callback_method);
// If Current Instance is the
// If overwrritten we'll have (2) instances, ignore the first.
if(m_num_instances == 1)
{
m_log.write<Logging::DEBUG_LOG>("DeadlineTimer() Executing CallBack",
"NumInstances=", (int)m_num_instances, "CurrInstance=", (int)c);
fun_callback(0);
}
else
{
m_log.write<Logging::DEBUG_LOG>("DeadlineTimer() Cancled CallBack",
"NumInstances=", (int)m_num_instances, "CurrInstance=", (int)c);
}
m_num_instances -= 1;
});
// Detach so there is no hold on the thread.
time_thread.detach();
}
/**
* @brief Blocking Wait (MilliSeconds), Sleeps then returns
*/
void wait()
{
std::this_thread::sleep_for(std::chrono::milliseconds(m_expires_from_now));
}
};
typedef std::shared_ptr<DeadlineTimer> deadline_timer_ptr;
//typedef std::unique_ptr<DeadlineTimer> deadline_timer_uptr;
#endif // DEADLINE_TIMER_HPP