HikoGUI
A low latency retained GUI
Loading...
Searching...
No Matches
timer.hpp
1// Copyright Take Vos 2020.
2// Distributed under the Boost Software License, Version 1.0.
3// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
4
5
6#pragma once
7
8#include "hires_utc_clock.hpp"
9#include <mutex>
10#include <vector>
11#include <functional>
12#include <tuple>
13#include <thread>
14
15namespace tt {
16
19class timer {
20public:
23
30
34
35public:
36 timer(std::string name) noexcept;
37 ~timer();
38
43 void start() noexcept;
44
49 void stop() noexcept;
50
63 template<typename Callback>
64 [[nodiscard]] std::shared_ptr<callback_type> add_callback(duration interval, Callback callback) noexcept
65 {
66 ttlet lock = std::scoped_lock(mutex);
67 ttlet current_time = hires_utc_clock::now();
68
69 auto callback_ptr = std::make_shared<callback_type>(std::forward<Callback>(callback));
70
71 callback_list.emplace_back(
73 calculate_next_wakeup(current_time, interval),
74 callback_ptr
75 );
76
77 if (std::ssize(callback_list) == 1) {
78 start_with_lock_held();
79 }
80
81 return callback_ptr;
82 }
83
86 void remove_callback(callback_ptr_type const &callback_ptr) noexcept;
87
88private:
89 struct callback_entry {
91 time_point next_wakeup;
93
94 callback_entry(duration interval, time_point next_wakeup, std::shared_ptr<callback_type> const &callback_ptr) noexcept :
95 interval(interval), next_wakeup(next_wakeup), callback_ptr(callback_ptr)
96 {
97 }
98 };
99
102 std::string name;
103
104 mutable std::mutex mutex;
105 std::thread thread;
106 std::vector<callback_entry> callback_list;
107 size_t callback_count = 0;
108
111 bool stop_thread;
112
119 find_triggered_callbacks(timer::time_point current_time) noexcept;
120
123 void loop() noexcept;
124
129 void start_with_lock_held() noexcept;
130
135 void stop_with_lock_held() noexcept;
136
137 [[nodiscard]] static time_point calculate_next_wakeup(time_point current_time, duration interval) noexcept;
138};
139
140
141}
STL namespace.
Definition interval.hpp:17
A timer which will execute callbacks at given intervals.
Definition timer.hpp:19
std::shared_ptr< callback_type > add_callback(duration interval, Callback callback) noexcept
Add a callback function to be executed each interval.
Definition timer.hpp:64
void stop() noexcept
Stop the timer thread.
void remove_callback(callback_ptr_type const &callback_ptr) noexcept
Remove the callback function.
void start() noexcept
Start the timer thread.
static std::unique_ptr< timer > global
Global maintenance timer.
Definition timer.hpp:33
T emplace_back(T... args)