Timer.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Function.h>
  8. #include <LibCore/Object.h>
  9. namespace Core {
  10. class Timer final : public Object {
  11. C_OBJECT(Timer);
  12. public:
  13. static NonnullRefPtr<Timer> create_repeating(int interval_ms, Function<void()>&& timeout_handler, Object* parent = nullptr)
  14. {
  15. auto timer = adopt_ref(*new Timer(interval_ms, move(timeout_handler), parent));
  16. timer->stop();
  17. return timer;
  18. }
  19. static NonnullRefPtr<Timer> create_single_shot(int interval_ms, Function<void()>&& timeout_handler, Object* parent = nullptr)
  20. {
  21. auto timer = adopt_ref(*new Timer(interval_ms, move(timeout_handler), parent));
  22. timer->set_single_shot(true);
  23. timer->stop();
  24. return timer;
  25. }
  26. virtual ~Timer() override;
  27. void start();
  28. void start(int interval_ms);
  29. void restart();
  30. void restart(int interval_ms);
  31. void stop();
  32. bool is_active() const { return m_active; }
  33. int interval() const { return m_interval_ms; }
  34. void set_interval(int interval_ms)
  35. {
  36. if (m_interval_ms == interval_ms)
  37. return;
  38. m_interval_ms = interval_ms;
  39. m_interval_dirty = true;
  40. }
  41. bool is_single_shot() const { return m_single_shot; }
  42. void set_single_shot(bool single_shot) { m_single_shot = single_shot; }
  43. Function<void()> on_timeout;
  44. private:
  45. explicit Timer(Object* parent = nullptr);
  46. Timer(int interval_ms, Function<void()>&& timeout_handler, Object* parent = nullptr);
  47. virtual void timer_event(TimerEvent&) override;
  48. bool m_active { false };
  49. bool m_single_shot { false };
  50. bool m_interval_dirty { false };
  51. int m_interval_ms { 0 };
  52. };
  53. }