Serenity Operating System
at master 81 lines 1.3 kB view raw
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#include <LibCore/Timer.h> 9 10namespace Core { 11 12Timer::Timer(Object* parent) 13 : Object(parent) 14{ 15} 16 17Timer::Timer(int interval_ms, Function<void()>&& timeout_handler, Object* parent) 18 : Object(parent) 19 , on_timeout(move(timeout_handler)) 20 , m_interval_ms(interval_ms) 21{ 22} 23 24void Timer::start() 25{ 26 start(m_interval_ms); 27} 28 29void Timer::start(int interval_ms) 30{ 31 if (m_active) 32 return; 33 m_interval_ms = interval_ms; 34 start_timer(interval_ms); 35 m_active = true; 36} 37 38void Timer::restart() 39{ 40 restart(m_interval_ms); 41} 42 43void Timer::restart(int interval_ms) 44{ 45 if (m_active) 46 stop(); 47 start(interval_ms); 48} 49 50void Timer::stop() 51{ 52 if (!m_active) 53 return; 54 stop_timer(); 55 m_active = false; 56} 57 58void Timer::set_active(bool active) 59{ 60 if (active) 61 start(); 62 else 63 stop(); 64} 65 66void Timer::timer_event(TimerEvent&) 67{ 68 if (m_single_shot) 69 stop(); 70 else { 71 if (m_interval_dirty) { 72 stop(); 73 start(m_interval_ms); 74 } 75 } 76 77 if (on_timeout) 78 on_timeout(); 79} 80 81}