Timer.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. Timer::Timer(EventReceiver* parent)
  10. : EventReceiver(parent)
  11. {
  12. }
  13. Timer::Timer(int interval_ms, Function<void()>&& timeout_handler, EventReceiver* parent)
  14. : EventReceiver(parent)
  15. , on_timeout(move(timeout_handler))
  16. , m_interval_ms(interval_ms)
  17. {
  18. }
  19. void Timer::start()
  20. {
  21. start(m_interval_ms);
  22. }
  23. void Timer::start(int interval_ms)
  24. {
  25. if (m_active)
  26. return;
  27. m_interval_ms = interval_ms;
  28. start_timer(interval_ms);
  29. m_active = true;
  30. }
  31. void Timer::restart()
  32. {
  33. restart(m_interval_ms);
  34. }
  35. void Timer::restart(int interval_ms)
  36. {
  37. if (m_active)
  38. stop();
  39. start(interval_ms);
  40. }
  41. void Timer::stop()
  42. {
  43. if (!m_active)
  44. return;
  45. stop_timer();
  46. m_active = false;
  47. }
  48. void Timer::set_active(bool active)
  49. {
  50. if (active)
  51. start();
  52. else
  53. stop();
  54. }
  55. void Timer::timer_event(TimerEvent&)
  56. {
  57. if (m_single_shot)
  58. stop();
  59. else {
  60. if (m_interval_dirty) {
  61. stop();
  62. start(m_interval_ms);
  63. }
  64. }
  65. if (on_timeout)
  66. on_timeout();
  67. }
  68. }