Timer.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. void set_active(bool);
  33. bool is_active() const { return m_active; }
  34. int interval() const { return m_interval_ms; }
  35. void set_interval(int interval_ms)
  36. {
  37. if (m_interval_ms == interval_ms)
  38. return;
  39. m_interval_ms = interval_ms;
  40. m_interval_dirty = true;
  41. }
  42. bool is_single_shot() const { return m_single_shot; }
  43. void set_single_shot(bool single_shot) { m_single_shot = single_shot; }
  44. Function<void()> on_timeout;
  45. private:
  46. explicit Timer(Object* parent = nullptr);
  47. Timer(int interval_ms, Function<void()>&& timeout_handler, Object* parent = nullptr);
  48. virtual void timer_event(TimerEvent&) override;
  49. bool m_active { false };
  50. bool m_single_shot { false };
  51. bool m_interval_dirty { false };
  52. int m_interval_ms { 0 };
  53. };
  54. }