summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibCore/Timer.cpp
blob: cf5a35ac17e79c10a792294f3fe17d3704ac496e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <LibCore/Timer.h>

namespace Core {

Timer::Timer(Object* parent)
    : Object(parent)
{
}

Timer::Timer(int interval_ms, Function<void()>&& timeout_handler, Object* parent)
    : Object(parent)
    , on_timeout(move(timeout_handler))
{
    start(interval_ms);
}

Timer::~Timer()
{
}

void Timer::start()
{
    start(m_interval_ms);
}

void Timer::start(int interval_ms)
{
    if (m_active)
        return;
    m_interval_ms = interval_ms;
    start_timer(interval_ms);
    m_active = true;
}

void Timer::restart()
{
    restart(m_interval_ms);
}

void Timer::restart(int interval_ms)
{
    if (m_active)
        stop();
    start(interval_ms);
}

void Timer::stop()
{
    if (!m_active)
        return;
    stop_timer();
    m_active = false;
}

void Timer::timer_event(TimerEvent&)
{
    if (m_single_shot)
        stop();
    else {
        if (m_interval_dirty) {
            stop();
            start(m_interval_ms);
        }
    }

    if (on_timeout)
        on_timeout();
}

}