Timer.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright (c) 2018-2024, 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/EventReceiver.h>
  10. namespace Core {
  11. class Timer final : public EventReceiver {
  12. C_OBJECT(Timer);
  13. public:
  14. static NonnullRefPtr<Timer> create();
  15. static NonnullRefPtr<Timer> create_repeating(int interval_ms, Function<void()>&& timeout_handler, EventReceiver* parent = nullptr);
  16. static NonnullRefPtr<Timer> create_single_shot(int interval_ms, Function<void()>&& timeout_handler, EventReceiver* parent = nullptr);
  17. virtual ~Timer() override;
  18. void start();
  19. void start(int interval_ms);
  20. void restart();
  21. void restart(int interval_ms);
  22. void stop();
  23. void set_active(bool);
  24. bool is_active() const { return m_active; }
  25. int interval() const { return m_interval_ms; }
  26. void set_interval(int interval_ms)
  27. {
  28. if (m_interval_ms == interval_ms)
  29. return;
  30. m_interval_ms = interval_ms;
  31. m_interval_dirty = true;
  32. }
  33. bool is_single_shot() const { return m_single_shot; }
  34. void set_single_shot(bool single_shot) { m_single_shot = single_shot; }
  35. Function<void()> on_timeout;
  36. private:
  37. explicit Timer(EventReceiver* parent = nullptr);
  38. Timer(int interval_ms, Function<void()>&& timeout_handler, EventReceiver* parent = nullptr);
  39. virtual void timer_event(TimerEvent&) override;
  40. bool m_active { false };
  41. bool m_single_shot { false };
  42. bool m_interval_dirty { false };
  43. int m_interval_ms { 0 };
  44. };
  45. }