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