| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- #ifndef UTIL_TIMER_H
- #define UTIL_TIMER_H
- #include <iostream>
- #include <atomic>
- #include <functional>
- #include <thread>
- namespace PresenceDetection {
- namespace Util {
- class Timer
- {
- public:
- Timer();
- ~Timer();
- bool operator==(const Timer& other) const;
- public:
- std::string Identifier() const;
- template <typename ...FunctionArguments, typename ...Arguments>
- void Start(int interval, std::function<void(FunctionArguments...)> const & function, Arguments && ...arguments)
- {
- 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 ...]()
- {
- while (m_run.load(std::memory_order_acquire))
- {
- function(std::forward<Arguments>(arguments)...);
- std::this_thread::sleep_for(std::chrono::milliseconds(interval));
- }
- });
- }
- void Stop();
- bool IsRunning() const noexcept;
- void Wait();
- private:
- std::atomic<bool> m_run;
- std::string m_identifier;
- std::thread m_thread;
- };
- } // namespace Util
- } // namespace PresenceDetection
- #endif // UTIL_TIMER_H
|