CountdownTimer.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #pragma once
  2. #include "../C/Baselib_CountdownTimer.h"
  3. #include "Time.h"
  4. namespace baselib
  5. {
  6. BASELIB_CPP_INTERFACE
  7. {
  8. class CountdownTimer
  9. {
  10. public:
  11. //
  12. // Create a countdown timer that already expired.
  13. //
  14. // Guaranteed to not sample the system timer.
  15. //
  16. static CountdownTimer InitializeExpired()
  17. {
  18. return CountdownTimer();
  19. }
  20. //
  21. // Create and start a countdown timer.
  22. //
  23. static CountdownTimer StartNew(const high_precision_clock::duration timeout)
  24. {
  25. return CountdownTimer(timeout);
  26. }
  27. //
  28. // Get time left before timeout expires.
  29. //
  30. // This function is guaranteed to return zero once timeout expired.
  31. // It is also guaranteed that this function will not return zero until timeout expires.
  32. // Return the time left as a high precision duration.
  33. //
  34. high_precision_clock::duration GetTimeLeft() const
  35. {
  36. return high_precision_clock::duration_from_ticks(Baselib_CountdownTimer_GetTimeLeftInTicks(m_CountdownTimer));
  37. }
  38. //
  39. // Get time left before timeout expires.
  40. //
  41. // This function is guaranteed to return zero once timeout expired.
  42. // It is also guaranteed that this function will not return zero until timeout expires.
  43. // Return the time left as a millisecond integer duration.
  44. //
  45. timeout_ms GetTimeLeftInMilliseconds() const
  46. {
  47. return timeout_ms(Baselib_CountdownTimer_GetTimeLeftInMilliseconds(m_CountdownTimer));
  48. }
  49. //
  50. // Check if timout has been reached.
  51. //
  52. bool TimeoutExpired() const
  53. {
  54. return Baselib_CountdownTimer_TimeoutExpired(m_CountdownTimer);
  55. }
  56. private:
  57. CountdownTimer() : m_CountdownTimer{0, 0} {}
  58. CountdownTimer(const high_precision_clock::duration timeout) : m_CountdownTimer(Baselib_CountdownTimer_StartTicks(high_precision_clock::ticks_from_duration_roundup(timeout))) {}
  59. Baselib_CountdownTimer m_CountdownTimer;
  60. };
  61. }
  62. }