zoom_video_sdk_node_timer.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #ifndef TIMER_H_
  2. #define TIMER_H_
  3. #include<functional>
  4. #include<chrono>
  5. #include<thread>
  6. #include<atomic>
  7. #include<memory>
  8. #include<mutex>
  9. #include<condition_variable>
  10. class NodeTimer {
  11. public:
  12. NodeTimer() :expired_(true), try_to_expire_(false) {
  13. }
  14. NodeTimer(const NodeTimer& t) {
  15. expired_ = t.expired_.load();
  16. try_to_expire_ = t.try_to_expire_.load();
  17. }
  18. ~NodeTimer() {
  19. StopTimer();
  20. }
  21. void StartTimer(int interval, std::function<void()> task) {
  22. if (expired_ == false) {
  23. return;
  24. }
  25. expired_ = false;
  26. std::thread([this, interval, task]() {
  27. while (!try_to_expire_) {
  28. std::this_thread::sleep_for(std::chrono::milliseconds(interval));
  29. task();
  30. }
  31. //
  32. {
  33. std::lock_guard<std::mutex> locker(mutex_);
  34. expired_ = true;
  35. expired_cond_.notify_one();
  36. }
  37. }).detach();
  38. }
  39. void StopTimer() {
  40. if (expired_) {
  41. return;
  42. }
  43. if (try_to_expire_) {
  44. //
  45. return;
  46. }
  47. try_to_expire_ = true;
  48. {
  49. std::unique_lock<std::mutex> locker(mutex_);
  50. expired_cond_.wait(locker, [this] {return expired_ == true; });
  51. if (expired_ == true) {
  52. //
  53. try_to_expire_ = false;
  54. }
  55. }
  56. }
  57. //the following 2 functions can be removed from the class because we will not use them
  58. template<typename callable, class... arguments>
  59. void SyncWait(int after, callable&& f, arguments&&... args) {
  60. std::function<typename std::result_of<callable(arguments...)>::type()> task
  61. (std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
  62. std::this_thread::sleep_for(std::chrono::milliseconds(after));
  63. task();
  64. }
  65. template<typename callable, class... arguments>
  66. void AsyncWait(int after, callable&& f, arguments&&... args) {
  67. std::function<typename std::result_of<callable(arguments...)>::type()> task
  68. (std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
  69. std::thread([after, task]() {
  70. std::this_thread::sleep_for(std::chrono::milliseconds(after));
  71. task();
  72. }).detach();
  73. }
  74. private:
  75. std::atomic<bool> expired_;
  76. std::atomic<bool> try_to_expire_;
  77. std::mutex mutex_;
  78. std::condition_variable expired_cond_;
  79. };
  80. #endif