|
|
@@ -1,11 +1,10 @@
|
|
|
#ifndef UTIL_TIMER_H
|
|
|
#define UTIL_TIMER_H
|
|
|
|
|
|
-#include <iostream>
|
|
|
-
|
|
|
#include <atomic>
|
|
|
#include <functional>
|
|
|
#include <thread>
|
|
|
+#include "Helpers.h"
|
|
|
|
|
|
|
|
|
namespace PresenceDetection {
|
|
|
@@ -17,31 +16,74 @@ public:
|
|
|
Timer();
|
|
|
~Timer();
|
|
|
|
|
|
+ Timer(const Timer&) = delete;
|
|
|
+ Timer& operator= (const Timer&) = delete;
|
|
|
+
|
|
|
+ Timer(Timer&& other);
|
|
|
+ Timer& operator= (Timer&& other);
|
|
|
+
|
|
|
bool operator==(const Timer& other) const;
|
|
|
+ bool operator==(const std::string& identifier) const;
|
|
|
|
|
|
public:
|
|
|
std::string Identifier() const;
|
|
|
|
|
|
template <typename ...FunctionArguments, typename ...Arguments>
|
|
|
- void Start(int interval, std::function<void(FunctionArguments...)> const & function, Arguments && ...arguments)
|
|
|
+ void StartSingle(int interval, std::function<void(FunctionArguments...)> const & function, Arguments && ...arguments)
|
|
|
+ {
|
|
|
+ Start(TimerType::Single, interval, function, std::forward<Arguments>(arguments)...);
|
|
|
+ }
|
|
|
+
|
|
|
+ template <typename ...FunctionArguments, typename ...Arguments>
|
|
|
+ void StartContinuous(int interval, std::function<void(FunctionArguments...)> const & function, Arguments && ...arguments)
|
|
|
+ {
|
|
|
+ Start(TimerType::Continuous, interval, function, std::forward<Arguments>(arguments)...);
|
|
|
+ }
|
|
|
+
|
|
|
+ void Stop();
|
|
|
+ bool IsRunning() const noexcept;
|
|
|
+ void Wait();
|
|
|
+
|
|
|
+private:
|
|
|
+ class TimerType
|
|
|
+ {
|
|
|
+ public:
|
|
|
+ enum type
|
|
|
+ {
|
|
|
+ Unknown,
|
|
|
+ Single,
|
|
|
+ Continuous
|
|
|
+ };
|
|
|
+ };
|
|
|
+
|
|
|
+private:
|
|
|
+ template <typename ...FunctionArguments, typename ...Arguments>
|
|
|
+ void Start(TimerType::type type, int interval, std::function<void(FunctionArguments...)> const & function, Arguments && ...arguments)
|
|
|
{
|
|
|
+ if (type == TimerType::Unknown)
|
|
|
+ return;
|
|
|
+
|
|
|
if (m_run.load(std::memory_order_acquire))
|
|
|
Stop();
|
|
|
|
|
|
- m_run.store(true, std::memory_order_release);
|
|
|
m_thread = std::thread([this, interval, function, &arguments...]()
|
|
|
{
|
|
|
+ auto argumentsCopy = std::make_tuple(std::forward<Arguments>(arguments)...);
|
|
|
+ m_run.store(true, std::memory_order_release);
|
|
|
+
|
|
|
while (m_run.load(std::memory_order_acquire))
|
|
|
{
|
|
|
- function(std::forward<Arguments>(arguments)...);
|
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
|
|
|
+ Helpers::execute(function, argumentsCopy);
|
|
|
+ if (TimerType::Single)
|
|
|
+ m_run.store(false, std::memory_order_release);
|
|
|
}
|
|
|
});
|
|
|
- }
|
|
|
|
|
|
- void Stop();
|
|
|
- bool IsRunning() const noexcept;
|
|
|
- void Wait();
|
|
|
+ while (!IsRunning())
|
|
|
+ {
|
|
|
+ }
|
|
|
+ }
|
|
|
|
|
|
private:
|
|
|
std::atomic<bool> m_run;
|