VLink  2.3.0
A high-performance communication middleware
timer.h
浏览该文件的文档.
1 /*
2  * Copyright (C) 2026 by Thun Lu. All rights reserved.
3  * Author: Thun Lu <thun.lu@zohomail.cn>
4  * Repo: https://github.com/thun-res/vlink
5  * _ __ __ _ __
6  * | | / / / / (_) ____ / /__
7  * | | / / / / / / / __ \ / //_/
8  * | |/ / / /___ / / / / / / / ,<
9  * |___/ /_____/ /_/ /_/ /_/ /_/|_|
10  *
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  * http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  */
23 
24 /**
25  * @file timer.h
26  * @brief MessageLoop-driven periodic or one-shot timer with priority support.
27  *
28  * @details
29  * @c vlink::Timer dispatches its callback on a @c MessageLoop thread, so the callback
30  * runs serially with every other task posted to the same loop and no additional
31  * synchronisation is required inside the callback body.
32  *
33  * Timer modes determined by @c loop_count:
34  *
35  * | Mode | @c loop_count value | Behaviour |
36  * | --------- | ------------------- | -------------------------------------------- |
37  * | One-shot | @c 1 | Fires exactly once after one full interval |
38  * | Counted | @c 2 ... @c INT_MAX | Fires the configured number of times |
39  * | Repeating | @c kInfinite (-1) | Fires forever until @c stop() is called |
40  *
41  * Key features:
42  * - Strict mode: when the loop falls behind, missed ticks are dispatched immediately on
43  * the next iteration so the long-term cadence is preserved.
44  * - Configurable dispatch priority for use with @c kPriorityType message loops.
45  * - When @c interval_ms is @c 0 the internal interval clamps to @c kMinInterval
46  * (10000 ns = 10 us) to avoid pathological busy-spinning; the effective rate is further
47  * bounded by the platform's wait resolution, about 1 ms or coarser on Windows and QNX.
48  * - The static @c call_once() helper posts a fire-and-forget one-shot without managing a
49  * @c Timer object.
50  *
51  * @par Lifecycle
52  * Construct -> @c attach() (if not done at construction) -> @c start() -> repeated ticks
53  * -> @c stop() / @c restart() / destruction.
54  *
55  * @par Example
56  * @code
57  * vlink::MessageLoop loop;
58  * vlink::Timer timer(&loop, 500, vlink::Timer::kInfinite, [] {
59  * handle_tick();
60  * });
61  * timer.start();
62  * loop.run();
63  * @endcode
64  */
65 
66 #pragma once
67 
68 #include <atomic>
69 #include <cstdint>
70 #include <memory>
71 
72 #include "./functional.h"
73 #include "./macros.h"
74 
75 namespace vlink {
76 
77 /**
78  * @class Timer
79  * @brief Periodic or one-shot timer that fires on an associated @c MessageLoop thread.
80  *
81  * @details
82  * Owns an internal implementation that integrates with the loop's tick scheduling so the
83  * callback runs in-line with every other task posted to the loop.
84  */
85 class VLINK_EXPORT Timer final {
86  public:
87  /**
88  * @brief Callback signature invoked on every tick.
89  */
90  using Callback = MoveFunction<void()>;
91 
92  /**
93  * @brief Sentinel @c loop_count value meaning fire forever.
94  */
95  static constexpr int kInfinite{-1};
96 
97  /**
98  * @brief Constructs a detached timer with a 1000 ms interval and no callback.
99  *
100  * @details
101  * Use @c attach() and @c set_callback() before @c start().
102  */
103  explicit Timer();
104 
105  /**
106  * @brief Constructs a timer attached to @p message_loop with the default interval and no callback.
107  *
108  * @param message_loop Loop that will dispatch ticks.
109  */
110  explicit Timer(class MessageLoop* message_loop);
111 
112  /**
113  * @brief Constructs a fully configured timer attached to a loop.
114  *
115  * @param message_loop Loop that will dispatch ticks.
116  * @param interval_ms Tick interval in milliseconds; @c 0 clamps to @c kMinInterval.
117  * @param loop_count Number of ticks to fire; @c kInfinite repeats forever. Default: @c kInfinite.
118  * @param callback Callback to install. Default: empty.
119  */
120  explicit Timer(class MessageLoop* message_loop, uint32_t interval_ms, int32_t loop_count = kInfinite,
121  Callback&& callback = nullptr);
122 
123  /**
124  * @brief Constructs a detached timer with explicit interval and loop count.
125  *
126  * @param interval_ms Tick interval in milliseconds; @c 0 clamps to @c kMinInterval.
127  * @param loop_count Number of ticks to fire; @c kInfinite repeats forever. Default: @c kInfinite.
128  * @param callback Callback to install. Default: empty.
129  */
130  explicit Timer(uint32_t interval_ms, int32_t loop_count = kInfinite, Callback&& callback = nullptr);
131 
132  /**
133  * @brief Destructor. Calls @c stop() and detaches the timer.
134  *
135  * @details
136  * Waits for a callback that is still executing on another thread. Destroying the
137  * timer from inside its own callback is not supported.
138  */
140 
141  /**
142  * @brief Posts a fire-and-forget one-shot timer to a loop.
143  *
144  * @details
145  * The timer fires exactly once @p interval_ms milliseconds later and is then destroyed
146  * automatically. Convenient when lifetime management of a long-lived @c Timer object
147  * would be inconvenient.
148  *
149  * @param message_loop Loop that will dispatch the tick.
150  * @param interval_ms Delay in milliseconds.
151  * @param callback Callback to invoke.
152  * @param priority Dispatch priority; @c 0 keeps the default. Default: @c 0.
153  * @return @c true on success.
154  */
155  static bool call_once(class MessageLoop* message_loop, uint32_t interval_ms, Callback&& callback,
156  uint16_t priority = 0);
157 
158  /**
159  * @brief Reports whether the timer is currently armed.
160  *
161  * @return @c true when the timer is running.
162  */
163  [[nodiscard]] bool is_active() const;
164 
165  /**
166  * @brief Reports whether strict catch-up mode is enabled.
167  *
168  * @return @c true when missed ticks are fired back-to-back.
169  */
170  [[nodiscard]] bool is_strict() const;
171 
172  /**
173  * @brief Returns the configured tick interval in milliseconds.
174  *
175  * @return Interval.
176  */
177  [[nodiscard]] uint32_t get_interval() const;
178 
179  /**
180  * @brief Returns the configured total tick count.
181  *
182  * @return Loop count; @c kInfinite for indefinite repetition.
183  */
184  [[nodiscard]] int32_t get_loop_count() const;
185 
186  /**
187  * @brief Returns the number of ticks remaining before automatic stop.
188  *
189  * @return Remaining tick count; @c kInfinite when repeating forever.
190  */
191  [[nodiscard]] int32_t get_remain_loop_count() const;
192 
193  /**
194  * @brief Returns the number of ticks dispatched since the last @c start() or @c restart().
195  *
196  * @return Dispatched tick count.
197  */
198  [[nodiscard]] uint64_t get_invoke_count() const;
199 
200  /**
201  * @brief Returns the dispatch priority used with @c kPriorityType loops.
202  *
203  * @return Priority value.
204  */
205  [[nodiscard]] uint16_t get_priority() const;
206 
207  /**
208  * @brief Returns the loop the timer is currently attached to.
209  *
210  * @return Loop pointer; @c nullptr when detached.
211  */
212  [[nodiscard]] class MessageLoop* get_message_loop() const;
213 
214  /**
215  * @brief Attaches the timer to @p message_loop.
216  *
217  * @details
218  * Must be called before @c start() when no loop was provided at construction. A null
219  * pointer logs a fatal error and throws. Re-attaching detaches from any previous loop.
220  *
221  * @param message_loop Loop to attach to.
222  * @return @c true on success.
223  */
224  bool attach(class MessageLoop* message_loop);
225 
226  /**
227  * @brief Detaches the timer from its loop and stops it first.
228  *
229  * @return @c true on success.
230  */
231  bool detach();
232 
233  /**
234  * @brief Arms the timer and starts dispatching ticks.
235  *
236  * @details
237  * When @p callback is non-null it replaces the existing callback. The first tick fires
238  * after one full interval, not immediately. Starting a timer with no callback is a
239  * no-op for dispatch purposes.
240  *
241  * @param callback Optional callback replacement. Default: keep the existing callback.
242  */
243  void start(Callback&& callback = nullptr);
244 
245  /**
246  * @brief Resets the tick count and re-arms the timer as if newly started.
247  */
248  void restart();
249 
250  /**
251  * @brief Disarms the timer without destroying it.
252  *
253  * @details
254  * After @c stop() the timer can be re-armed by another @c start().
255  */
256  void stop();
257 
258  /**
259  * @brief Enables or disables strict catch-up firing.
260  *
261  * @param strict @c true to fire missed ticks back-to-back. Default state is @c false.
262  */
263  void set_strict(bool strict);
264 
265  /**
266  * @brief Updates the tick interval.
267  *
268  * @details
269  * Takes effect immediately for an active timer: the processed tick count is recomputed
270  * against the existing start time and the loop is woken. @p interval_ms @c == @c 0
271  * clamps the internal interval to @c kMinInterval (10000 ns = 10 us).
272  *
273  * @param interval_ms New interval in milliseconds.
274  */
275  void set_interval(uint32_t interval_ms);
276 
277  /**
278  * @brief Updates the total tick count.
279  *
280  * @param loop_count New loop count; @c kInfinite for indefinite repetition.
281  */
282  void set_loop_count(int32_t loop_count);
283 
284  /**
285  * @brief Replaces the callback dispatched on every tick.
286  *
287  * @param callback New callback.
288  */
289  void set_callback(Callback&& callback);
290 
291  /**
292  * @brief Updates the dispatch priority.
293  *
294  * @details
295  * Only effective when the associated loop is of type @c kPriorityType.
296  *
297  * @param priority Priority value; higher fires sooner.
298  */
299  void set_priority(uint16_t priority);
300 
301  private:
302  void run_callback();
303 
304  void begin_in_flight();
305 
306  void end_in_flight();
307 
308  void wait_for_idle();
309 
310  void stop(bool invalidate_pending);
311 
312  void clear();
313 
314  void force_to_start(bool reset_loop_count = false);
315 
316  void set_remain_loop_count(int32_t loop_count) const;
317 
318  void sub_remain_loop_count() const;
319 
320  void set_invoke_count(uint64_t invoke_count) const;
321 
322  uint64_t get_start_time() const;
323 
324  uint64_t get_generation() const;
325 
326  bool is_once_type() const;
327 
328  bool has_callback() const;
329 
330  Callback take_callback();
331 
332  std::shared_ptr<std::atomic_bool> get_alive_flag() const;
333 
334  friend class MessageLoop;
335  struct Impl;
336  std::unique_ptr<Impl> impl_;
337  static constexpr uint32_t kMinInterval{10'000U};
338 
340 };
341 
342 } // namespace vlink
Pool-backed type-erased callables: copyable vlink::Function and move-only vlink::MoveFunction.
Cross-platform macros for visibility, branch hints, copy prevention, singletons and string helpers.
#define VLINK_EXPORT
Definition: macros.h:81
#define VLINK_DISALLOW_COPY_AND_ASSIGN(classname)
Deletes the copy constructor and copy-assignment operator of classname.
Definition: macros.h:174