alive_time_cp.hpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright (c) 2017-2023 zhllxt
  3. *
  4. * author : zhllxt
  5. * email : 37792738@qq.com
  6. *
  7. * Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. */
  10. #ifndef __ASIO2_ALIVE_TIME_COMPONENT_HPP__
  11. #define __ASIO2_ALIVE_TIME_COMPONENT_HPP__
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. #pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <chrono>
  16. namespace asio2::detail
  17. {
  18. template<class derived_t, class args_t>
  19. class alive_time_cp
  20. {
  21. public:
  22. /**
  23. * @brief constructor
  24. */
  25. alive_time_cp() = default;
  26. /**
  27. * @brief destructor
  28. */
  29. ~alive_time_cp() = default;
  30. alive_time_cp(alive_time_cp&&) noexcept = default;
  31. alive_time_cp(alive_time_cp const&) = default;
  32. alive_time_cp& operator=(alive_time_cp&&) noexcept = default;
  33. alive_time_cp& operator=(alive_time_cp const&) = default;
  34. public:
  35. /**
  36. * @brief get the time when the last alive event occurred, same as get_last_alive_time
  37. */
  38. inline std::chrono::time_point<std::chrono::system_clock> last_alive_time() const noexcept
  39. {
  40. return this->get_last_alive_time();
  41. }
  42. /**
  43. * @brief get the time when the last alive event occurred
  44. */
  45. inline std::chrono::time_point<std::chrono::system_clock> get_last_alive_time() const noexcept
  46. {
  47. return this->last_alive_time_;
  48. }
  49. /**
  50. * @brief reset last alive time to system_clock::now()
  51. */
  52. inline derived_t & update_alive_time() noexcept
  53. {
  54. this->last_alive_time_ = std::chrono::system_clock::now();
  55. return (static_cast<derived_t &>(*this));
  56. }
  57. /**
  58. * @brief get silence duration of std::chrono::duration
  59. */
  60. inline std::chrono::system_clock::duration get_silence_duration() const noexcept
  61. {
  62. return std::chrono::duration_cast<std::chrono::system_clock::duration>(
  63. std::chrono::system_clock::now() - this->last_alive_time_);
  64. }
  65. protected:
  66. /// last alive time
  67. decltype(std::chrono::system_clock::now()) last_alive_time_ = std::chrono::system_clock::now();
  68. };
  69. }
  70. #endif // !__ASIO2_ALIVE_TIME_COMPONENT_HPP__