Timer.cpp 1.2 KB

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