galaxy 1.0.0
Real-Time C++23 Game Programming Framework. Built on data-driven design principles and agile software engineering.
Loading...
Searching...
No Matches
Timer.cpp
Go to the documentation of this file.
1
7
8#include <BS_thread_pool.hpp>
9#include <entt/locator/locator.hpp>
10
12
13#include "Timer.hpp"
14
15using namespace std::chrono_literals;
16
17namespace galaxy
18{
19 Timer::Timer() noexcept
20 : m_started {false}
21 , m_paused {false}
22 , m_repeat {false}
23 , m_delay {1000}
24 , m_handle {}
25 , m_callback {nullptr}
26 {
27 }
28
29 Timer::~Timer() noexcept
30 {
31 stop();
32 }
33
34 void Timer::set(Timer::Function&& func, const std::uint64_t delay) noexcept
35 {
36 m_callback = std::move(func);
37 m_delay = delay;
38 }
39
40 void Timer::start(const bool repeat)
41 {
42 m_repeat = repeat;
43 if (!m_started)
44 {
45 m_started = true;
46 m_paused = false;
47
48 auto& tp = entt::locator<BS::light_thread_pool>::value();
49 m_handle = tp.submit_task([&]() {
50 do
51 {
52 if (!m_paused && m_started)
53 {
54 std::this_thread::sleep_for(std::chrono::milliseconds(m_delay));
55 m_callback();
56 }
57 else
58 {
59 // Prevent excess CPU usage.
60 std::this_thread::sleep_for(0.01ms);
61 }
62 } while (m_repeat);
63 });
64 }
65 }
66
67 void Timer::stop() noexcept
68 {
69 m_started = false;
70 m_paused = false;
71 m_repeat = false;
72
74 {
75 std::this_thread::sleep_for(0.01ms);
76 }
77 }
78
79 void Timer::pause(const bool pause) noexcept
80 {
81 m_paused = pause;
82 }
83
84 bool Timer::stopped() const noexcept
85 {
86 return !m_started;
87 }
88
89 bool Timer::paused() const noexcept
90 {
91 return m_paused && m_started;
92 }
93} // namespace galaxy
std::atomic_bool m_started
Has the timer been started.
Definition Timer.hpp:94
void stop() noexcept
Stop timer.
Definition Timer.cpp:67
std::future< void > m_handle
Thread running task.
Definition Timer.hpp:114
std::atomic_bool m_repeat
Is timer looping.
Definition Timer.hpp:104
Timer() noexcept
Constructor.
Definition Timer.cpp:19
Timer::Function m_callback
Callback function.
Definition Timer.hpp:119
void pause(const bool pause) noexcept
Pause the timer.
Definition Timer.cpp:79
void start(const bool repeat=false)
Start timer.
Definition Timer.cpp:40
std::atomic_bool m_paused
Is timer paused.
Definition Timer.hpp:99
bool paused() const noexcept
Is the timer paused?
Definition Timer.cpp:89
std::move_only_function< void(void)> Function
Timer callback type.
Definition Timer.hpp:24
void set(Timer::Function &&func, const std::uint64_t delay) noexcept
Run a function on a precision timer.
Definition Timer.cpp:34
std::uint64_t m_delay
Current delay on timer.
Definition Timer.hpp:109
bool stopped() const noexcept
Is the timer finished?
Definition Timer.cpp:84
~Timer() noexcept
Destructor.
Definition Timer.cpp:29
bool is_work_done(const std::future< T > &task) noexcept
Check if an async thread has finished or not.
Definition Async.hpp:31
Animated.cpp galaxy.
Definition Animated.cpp:16