Timer.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. #pragma once
  8. #include <AK/Function.h>
  9. #include <LibCore/Object.h>
  10. namespace Core {
  11. class Timer final : public Object {
  12. C_OBJECT(Timer);
  13. public:
  14. static NonnullRefPtr<Timer> create_repeating(int interval_ms, Function<void()>&& timeout_handler, Object* parent = nullptr)
  15. {
  16. auto timer = adopt_ref(*new Timer(interval_ms, move(timeout_handler), parent));
  17. timer->stop();
  18. return timer;
  19. }
  20. static NonnullRefPtr<Timer> create_single_shot(int interval_ms, Function<void()>&& timeout_handler, Object* parent = nullptr)
  21. {
  22. auto timer = adopt_ref(*new Timer(interval_ms, move(timeout_handler), parent));
  23. timer->set_single_shot(true);
  24. timer->stop();
  25. return timer;
  26. }
  27. virtual ~Timer() override = default;
  28. void start();
  29. void start(int interval_ms);
  30. void restart();
  31. void restart(int interval_ms);
  32. void stop();
  33. void set_active(bool);
  34. bool is_active() const { return m_active; }
  35. int interval() const { return m_interval_ms; }
  36. void set_interval(int interval_ms)
  37. {
  38. if (m_interval_ms == interval_ms)
  39. return;
  40. m_interval_ms = interval_ms;
  41. m_interval_dirty = true;
  42. }
  43. bool is_single_shot() const { return m_single_shot; }
  44. void set_single_shot(bool single_shot) { m_single_shot = single_shot; }
  45. Function<void()> on_timeout;
  46. private:
  47. explicit Timer(Object* parent = nullptr);
  48. Timer(int interval_ms, Function<void()>&& timeout_handler, Object* parent = nullptr);
  49. virtual void timer_event(TimerEvent&) override;
  50. bool m_active { false };
  51. bool m_single_shot { false };
  52. bool m_interval_dirty { false };
  53. int m_interval_ms { 0 };
  54. };
  55. }