Timer.h 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #ifndef UTIL_TIMER_H
  2. #define UTIL_TIMER_H
  3. #include <iostream>
  4. #include <atomic>
  5. #include <functional>
  6. #include <thread>
  7. namespace PresenceDetection {
  8. namespace Util {
  9. class Timer
  10. {
  11. public:
  12. Timer();
  13. ~Timer();
  14. bool operator==(const Timer& other) const;
  15. public:
  16. std::string Identifier() const;
  17. template <typename ...FunctionArguments, typename ...Arguments>
  18. void Start(int interval, std::function<void(FunctionArguments...)> const & function, Arguments && ...arguments)
  19. {
  20. if (m_run.load(std::memory_order_acquire))
  21. Stop();
  22. m_run.store(true, std::memory_order_release);
  23. m_thread = std::thread([this, interval, function, arguments ...]()
  24. {
  25. while (m_run.load(std::memory_order_acquire))
  26. {
  27. function(std::forward<Arguments>(arguments)...);
  28. std::this_thread::sleep_for(std::chrono::milliseconds(interval));
  29. }
  30. });
  31. }
  32. void Stop();
  33. bool IsRunning() const noexcept;
  34. void Wait();
  35. private:
  36. std::atomic<bool> m_run;
  37. std::string m_identifier;
  38. std::thread m_thread;
  39. };
  40. } // namespace Util
  41. } // namespace PresenceDetection
  42. #endif // UTIL_TIMER_H