Timer.cpp 846 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include <chrono>
  2. #include "Timer.h"
  3. namespace PresenceDetection {
  4. namespace Util {
  5. Timer::Timer() :
  6. m_run(false)
  7. {
  8. }
  9. Timer::~Timer()
  10. {
  11. Stop();
  12. }
  13. void Timer::Start(int interval, std::function<void(void)> function)
  14. {
  15. if (m_run.load(std::memory_order_acquire))
  16. Stop();
  17. m_run.store(true, std::memory_order_release);
  18. m_thread = std::thread([this, interval, function]()
  19. {
  20. while (m_run.load(std::memory_order_acquire))
  21. {
  22. function();
  23. std::this_thread::sleep_for(std::chrono::milliseconds(interval));
  24. }
  25. });
  26. }
  27. void Timer::Stop()
  28. {
  29. m_run.store(false, std::memory_order_release);
  30. }
  31. bool Timer::IsRunning() const noexcept
  32. {
  33. return (m_run.load(std::memory_order_acquire) && m_thread.joinable());
  34. }
  35. void Timer::Wait()
  36. {
  37. if (m_thread.joinable())
  38. m_thread.join();
  39. }
  40. } // namespace Util
  41. } // namespace PresenceDetection