OpenTTD Source 20250521-master-g82876c25e0
timer_manager.h
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
11#ifndef TIMER_MANAGER_H
12#define TIMER_MANAGER_H
13
14template <typename TTimerType>
15class BaseTimer;
16
24template <typename TTimerType>
26public:
27 using TPeriod = typename TTimerType::TPeriod;
28 using TElapsed = typename TTimerType::TElapsed;
29
30 /* Avoid copying this object; it is a singleton object. */
31 TimerManager(TimerManager const &) = delete;
32 TimerManager &operator=(TimerManager const &) = delete;
33
40 {
41#ifdef WITH_ASSERT
42 Validate(timer.period);
43#endif /* WITH_ASSERT */
44 GetTimers().insert(&timer);
45 }
46
53 {
54 GetTimers().erase(&timer);
55 }
56
63 static void ChangeRegisteredTimerPeriod(BaseTimer<TTimerType> &timer, TPeriod new_period)
64 {
65 /* Unregistration and re-registration is necessary because the period is used as the sort key in base_timer_sorter */
66 UnregisterTimer(timer);
67 timer.period = new_period;
68 RegisterTimer(timer);
69 }
70
71#ifdef WITH_ASSERT
83 static void Validate(TPeriod period);
84#endif /* WITH_ASSERT */
85
95 static bool Elapsed(TElapsed value);
96
97private:
105 bool operator() (BaseTimer<TTimerType> *a, BaseTimer<TTimerType> *b) const
106 {
107 if (a->period == b->period) return a < b;
108 return a->period < b->period;
109 }
110 };
111
113 static std::set<BaseTimer<TTimerType> *, base_timer_sorter> &GetTimers()
114 {
115 static std::set<BaseTimer<TTimerType> *, base_timer_sorter> timers;
116 return timers;
117 }
118};
119
120#endif /* TIMER_MANAGER_H */
The base where every other type of timer is derived from.
Definition timer.h:22
TPeriod period
The period of the timer.
Definition timer.h:49
The TimerManager manages a single Timer-type.
static void UnregisterTimer(BaseTimer< TTimerType > &timer)
Unregister a timer.
static std::set< BaseTimer< TTimerType > *, base_timer_sorter > & GetTimers()
Singleton list, to store all the active timers.
static bool Elapsed(TElapsed value)
Called when time for this timer elapsed.
static void RegisterTimer(BaseTimer< TTimerType > &timer)
Register a timer.
static void ChangeRegisteredTimerPeriod(BaseTimer< TTimerType > &timer, TPeriod new_period)
Change the period of a registered timer.