Timer.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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::timer_event(TimerEvent&)
  51. {
  52. if (m_single_shot)
  53. stop();
  54. else {
  55. if (m_interval_dirty) {
  56. stop();
  57. start(m_interval_ms);
  58. }
  59. }
  60. if (on_timeout)
  61. on_timeout();
  62. }
  63. }