Timer.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibCore/Timer.h>
  8. namespace Core {
  9. NonnullRefPtr<Timer> Timer::create()
  10. {
  11. return adopt_ref(*new Timer);
  12. }
  13. NonnullRefPtr<Timer> Timer::create_repeating(int interval_ms, Function<void()>&& timeout_handler, EventReceiver* parent)
  14. {
  15. return adopt_ref(*new Timer(interval_ms, move(timeout_handler), parent));
  16. }
  17. NonnullRefPtr<Timer> Timer::create_single_shot(int interval_ms, Function<void()>&& timeout_handler, EventReceiver* parent)
  18. {
  19. auto timer = adopt_ref(*new Timer(interval_ms, move(timeout_handler), parent));
  20. timer->set_single_shot(true);
  21. return timer;
  22. }
  23. Timer::~Timer() = default;
  24. Timer::Timer(EventReceiver* parent)
  25. : EventReceiver(parent)
  26. {
  27. }
  28. Timer::Timer(int interval_ms, Function<void()>&& timeout_handler, EventReceiver* parent)
  29. : EventReceiver(parent)
  30. , on_timeout(move(timeout_handler))
  31. , m_interval_ms(interval_ms)
  32. {
  33. }
  34. void Timer::start()
  35. {
  36. start(m_interval_ms);
  37. }
  38. void Timer::start(int interval_ms)
  39. {
  40. if (m_active)
  41. return;
  42. m_interval_ms = interval_ms;
  43. start_timer(interval_ms);
  44. m_active = true;
  45. }
  46. void Timer::restart()
  47. {
  48. restart(m_interval_ms);
  49. }
  50. void Timer::restart(int interval_ms)
  51. {
  52. if (m_active)
  53. stop();
  54. start(interval_ms);
  55. }
  56. void Timer::stop()
  57. {
  58. if (!m_active)
  59. return;
  60. stop_timer();
  61. m_active = false;
  62. }
  63. void Timer::set_active(bool active)
  64. {
  65. if (active)
  66. start();
  67. else
  68. stop();
  69. }
  70. void Timer::timer_event(TimerEvent&)
  71. {
  72. if (m_single_shot)
  73. stop();
  74. else {
  75. if (m_interval_dirty) {
  76. stop();
  77. start(m_interval_ms);
  78. }
  79. }
  80. if (on_timeout)
  81. on_timeout();
  82. }
  83. }