2020-01-18 03:38:21 -05:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
|
2022-02-26 11:09:45 -05:00
|
|
|
* Copyright (c) 2022, the SerenityOS developers.
|
2020-01-18 03:38:21 -05:00
|
|
|
*
|
2021-04-22 04:24:48 -04:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-01-18 03:38:21 -05:00
|
|
|
*/
|
|
|
|
|
2020-02-06 09:04:03 -05:00
|
|
|
#include <LibCore/Timer.h>
|
2019-03-30 16:40:27 -04:00
|
|
|
|
2020-02-02 06:34:39 -05:00
|
|
|
namespace Core {
|
|
|
|
|
|
|
|
Timer::Timer(Object* parent)
|
|
|
|
: Object(parent)
|
2019-03-30 16:40:27 -04:00
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2021-05-10 05:29:41 -04:00
|
|
|
Timer::Timer(int interval_ms, Function<void()>&& timeout_handler, Object* parent)
|
2020-02-02 06:34:39 -05:00
|
|
|
: Object(parent)
|
2019-04-13 23:44:15 -04:00
|
|
|
, on_timeout(move(timeout_handler))
|
2023-01-11 14:36:46 -05:00
|
|
|
, m_interval_ms(interval_ms)
|
2019-04-13 23:44:15 -04:00
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2020-02-02 06:34:39 -05:00
|
|
|
void Timer::start()
|
2019-03-30 16:40:27 -04:00
|
|
|
{
|
2021-05-10 05:29:41 -04:00
|
|
|
start(m_interval_ms);
|
2019-03-30 16:40:27 -04:00
|
|
|
}
|
|
|
|
|
2021-05-10 05:29:41 -04:00
|
|
|
void Timer::start(int interval_ms)
|
2019-03-30 16:40:27 -04:00
|
|
|
{
|
|
|
|
if (m_active)
|
|
|
|
return;
|
2021-05-10 05:29:41 -04:00
|
|
|
m_interval_ms = interval_ms;
|
|
|
|
start_timer(interval_ms);
|
2019-03-30 16:40:27 -04:00
|
|
|
m_active = true;
|
|
|
|
}
|
|
|
|
|
2020-06-11 16:35:37 -04:00
|
|
|
void Timer::restart()
|
|
|
|
{
|
2021-05-10 05:29:41 -04:00
|
|
|
restart(m_interval_ms);
|
2020-06-11 16:35:37 -04:00
|
|
|
}
|
|
|
|
|
2021-05-10 05:29:41 -04:00
|
|
|
void Timer::restart(int interval_ms)
|
2019-04-17 22:38:04 -04:00
|
|
|
{
|
|
|
|
if (m_active)
|
|
|
|
stop();
|
2021-05-10 05:29:41 -04:00
|
|
|
start(interval_ms);
|
2019-04-17 22:38:04 -04:00
|
|
|
}
|
|
|
|
|
2020-02-02 06:34:39 -05:00
|
|
|
void Timer::stop()
|
2019-03-30 16:40:27 -04:00
|
|
|
{
|
|
|
|
if (!m_active)
|
|
|
|
return;
|
|
|
|
stop_timer();
|
|
|
|
m_active = false;
|
|
|
|
}
|
|
|
|
|
2021-12-25 07:25:24 -05:00
|
|
|
void Timer::set_active(bool active)
|
|
|
|
{
|
|
|
|
if (active)
|
|
|
|
start();
|
|
|
|
else
|
|
|
|
stop();
|
|
|
|
}
|
|
|
|
|
2020-02-02 06:34:39 -05:00
|
|
|
void Timer::timer_event(TimerEvent&)
|
2019-03-30 16:40:27 -04:00
|
|
|
{
|
|
|
|
if (m_single_shot)
|
|
|
|
stop();
|
2019-04-17 22:38:04 -04:00
|
|
|
else {
|
|
|
|
if (m_interval_dirty) {
|
|
|
|
stop();
|
2021-05-10 05:29:41 -04:00
|
|
|
start(m_interval_ms);
|
2019-04-17 22:38:04 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-30 16:40:27 -04:00
|
|
|
if (on_timeout)
|
|
|
|
on_timeout();
|
|
|
|
}
|
2020-02-02 06:34:39 -05:00
|
|
|
|
|
|
|
}
|