timer.h 680 B

12345678910111213141516171819202122232425262728293031323334353637
  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 Timer
  11. {
  12. public:
  13. Timer();
  14. Timer(const Timer& timer);
  15. ~Timer();
  16. public:
  17. void start(int interval, std::function<void()> task);
  18. void startOnce(int delay, std::function<void()> task);
  19. void stop();
  20. bool IsStop() const {return mStop;}
  21. bool mStop;
  22. private:
  23. std::atomic<bool> _expired; // timer stopped status
  24. std::atomic<bool> _try_to_expire; // timer is in stop process
  25. std::mutex _mutex;
  26. std::condition_variable _expired_cond;
  27. };
  28. #endif // TIMER_H