VLink 2.0.0
A high-performance communication middleware
载入中...
搜索中...
未找到
schedule.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 schedule.h
26 * @brief RAII task scheduling wrapper with delay, priority, timeouts and result chaining.
27 *
28 * @details
29 * @c Schedule is a utility namespace (implemented as a non-constructible struct) that wraps a
30 * callable in a @c Config envelope and produces a @c Status or @c RetStatus RAII handle.
31 * The handle lets callers register continuation callbacks in a fluent style:
32 *
33 * @code
34 * loop.exec_task(vlink::Schedule::Config{0, 100}, // no delay, priority 100
35 * []() -> bool { return do_work(); })
36 * .on_then([] { on_success(); })
37 * .on_else([] { on_failure(); })
38 * .on_catch([](std::exception& e) { on_error(e); })
39 * .on_schedule_timeout([] { on_not_started_in_time(); })
40 * .on_execution_timeout([] { on_took_too_long(); });
41 * @endcode
42 *
43 * Config fields:
44 *
45 * | Field | Meaning |
46 * | ----------------------- | -------------------------------------------------------------- |
47 * | @c delay_ms | Delay before the task is posted (via one-shot Timer) |
48 * | @c priority | Task dispatch priority (for @c kPriorityType loop) |
49 * | @c schedule_timeout_ms | If the task is not started within this time, fire the timeout |
50 * | @c execution_timeout_ms | If the task runs longer than this, fire the timeout callback |
51 *
52 * @note
53 * - @c Status is move-only; copying is disabled. The internal state is reference-counted
54 * via @c std::shared_ptr<StatusImpl>, so it is safe to return by value.
55 * - @c RetStatus adds @c on_then (fires when callback returns @c true) and @c on_else
56 * (fires when callback returns @c false).
57 * - Callbacks are invoked from the @c MessageLoop thread.
58 *
59 * @par Example
60 * @code
61 * vlink::MessageLoop loop;
62 * loop.async_run();
63 *
64 * // Void callback with execution timeout:
65 * loop.exec_task(vlink::Schedule::Config{100}, // 100 ms delay
66 * [] { expensive_op(); })
67 * .on_execution_timeout([] { VLOG_W("slow!"); });
68 *
69 * // Bool callback with result chaining:
70 * loop.exec_task(vlink::Schedule::Config{},
71 * []() -> bool { return try_connect(); })
72 * .on_then([] { start_session(); })
73 * .on_else([] { retry_later(); });
74 * @endcode
75 */
76
77#pragma once
78
79#include <atomic>
80#include <cstdint>
81#include <functional>
82#include <memory>
83#include <mutex>
84#include <vector>
85
86#include "./macros.h"
87
88namespace vlink {
89
90/**
91 * @struct Schedule
92 * @brief Non-constructible utility struct providing task scheduling primitives.
93 *
94 * @details
95 * Contains @c Config, @c Status, @c RetStatus, @c process() and @c process_with_ret().
96 * Users interact with this struct primarily via @c MessageLoop::exec_task().
97 */
98struct VLINK_EXPORT Schedule final {
99 /**
100 * @brief Callback type for void tasks and lifecycle hooks (schedule/execution timeout, else).
101 */
102 using Callback = std::function<void()>;
103
104 /**
105 * @brief Callback type for tasks that return a boolean result.
106 */
107 using RetCallback = std::function<bool()>;
108
109 /**
110 * @brief Callback type invoked when an exception is caught inside the task.
111 */
112 using CatchCallback = std::function<void(std::exception&)>;
113
114 /**
115 * @struct Config
116 * @brief Scheduling parameters for a task posted via @c MessageLoop::exec_task().
117 *
118 * @details
119 * All fields are optional; defaults result in immediate posting with no timeouts.
120 */
121 struct VLINK_EXPORT Config final {
122 /**
123 * @brief Constructs a default @c Config with all fields set to zero.
124 */
126
127 /**
128 * @brief Constructs a @c Config with all fields specified.
129 *
130 * @param _delay_ms Delay before posting in milliseconds. 0 = immediate.
131 * @param _priority Task dispatch priority. 0 = default.
132 * @param _schedule_timeout_ms Max wait before the task starts (0 = no timeout).
133 * @param _execution_timeout_ms Max execution time of the task (0 = no timeout).
134 */
135 explicit Config(uint32_t _delay_ms, uint16_t _priority = 0, uint32_t _schedule_timeout_ms = 0,
136 uint32_t _execution_timeout_ms = 0);
137
138 uint32_t delay_ms{0}; ///< Delay in ms before the task is posted.
139 uint16_t priority{0}; ///< Dispatch priority (higher = sooner).
140 uint32_t schedule_timeout_ms{0}; ///< Max ms to wait before task starts. 0 = disabled.
141 uint32_t execution_timeout_ms{0}; ///< Max ms the task may execute. 0 = disabled.
142 };
143
144 /**
145 * @class Status
146 * @brief RAII handle returned by @c exec_task() for a void-callback task.
147 *
148 * @details
149 * Holds a shared reference to the internal task state. Destruction does not
150 * cancel the task. Callback registration methods return @c *this to allow chaining.
151 */
153 public:
154 /**
155 * @brief Constructs an invalid @c Status (not yet associated with a task).
156 */
158
159 /**
160 * @brief Destructor.
161 */
163
164 Status(const Status&) = delete;
165
166 Status& operator=(const Status&) = delete;
167
168 /**
169 * @brief Move constructor.
170 *
171 * @param status Source status to move from.
172 */
173 Status(Status&& status) noexcept;
174
175 /**
176 * @brief Move assignment.
177 *
178 * @param status Source status to move from.
179 * @return Reference to @c *this.
180 */
181 Status& operator=(Status&& status) noexcept;
182
183 /**
184 * @brief Sets whether the status is valid (task was successfully posted).
185 *
186 * @param valid @c true if the associated task was posted successfully.
187 */
188 void set_valid(bool valid);
189
190 /**
191 * @brief Returns @c true if the associated task was posted successfully.
192 *
193 * @return @c true if valid.
194 */
195 [[nodiscard]] bool is_valid() const;
196
197 /**
198 * @brief Registers a callback fired when the task does not start within @c schedule_timeout_ms.
199 *
200 * @param callback Callback invoked from the loop thread on schedule timeout.
201 * @return Reference to @c *this for chaining.
202 */
204
205 /**
206 * @brief Registers a callback fired when the task runs longer than @c execution_timeout_ms.
207 *
208 * @param callback Callback invoked from the loop thread on execution timeout.
209 * @return Reference to @c *this for chaining.
210 */
212
213 /**
214 * @brief Registers a callback fired when the task throws an exception.
215 *
216 * @details
217 * The exception is caught inside the wrapper and passed to this callback.
218 * The task is considered failed after an exception.
219 *
220 * @param callback Callback invoked with the caught exception.
221 * @return Reference to @c *this for chaining.
222 */
224
225 protected:
226 friend Schedule;
227
237
238 std::shared_ptr<StatusImpl> impl_;
239 };
240
241 /**
242 * @class RetStatus
243 * @brief RAII handle returned by @c exec_task() for a bool-returning callback task.
244 *
245 * @details
246 * Extends @c Status with @c on_then (fired if callback returns @c true) and
247 * @c on_else (fired if callback returns @c false).
248 */
249 class VLINK_EXPORT RetStatus final : public Status {
250 public:
251 using Status::Status;
252
253 /**
254 * @brief Registers a callback fired when the task returns @c false.
255 *
256 * @param callback Invoked from the loop thread when the return value is @c false.
257 * @return Reference to the base @c Status for further chaining.
258 */
259 Status& on_else(Callback&& callback);
260
261 /**
262 * @brief Registers a callback chain element fired when the task returns @c true.
263 *
264 * @details
265 * Multiple @c on_then callbacks may be chained; each receives a @c bool return
266 * value from the previous callback in the chain.
267 *
268 * @param callback Callback taking no arguments and returning @c bool.
269 * @return Reference to @c *this for further @c on_then chaining.
270 */
272 };
273
274 Schedule() = delete;
275
276 Schedule(const Schedule&) = delete;
277
278 Schedule& operator=(const Schedule&) = delete;
279
280 Schedule(Schedule&&) = delete;
281
283
284 /**
285 * @brief Wraps a void callback in a @c Config envelope and produces a wrapper task.
286 *
287 * @details
288 * Called internally by @c MessageLoop::exec_task(). Creates the @c Status and
289 * populates @p wrapper_callback with the task wrapper ready to be posted to the queue.
290 *
291 * @param config Scheduling configuration.
292 * @param callback Void callable to execute.
293 * @param wrapper_callback Output: the wrapped task to be posted.
294 * @return @c Status handle for chaining callbacks.
295 */
296 [[nodiscard]] static Status process(const Config& config, Callback&& callback, Callback& wrapper_callback);
297
298 /**
299 * @brief Wraps a bool-returning callback in a @c Config envelope and produces a wrapper task.
300 *
301 * @details
302 * Called internally by @c MessageLoop::exec_task(). Creates the @c RetStatus and
303 * populates @p wrapper_callback with the task wrapper ready to be posted to the queue.
304 *
305 * @param config Scheduling configuration.
306 * @param callback Bool-returning callable to execute.
307 * @param wrapper_callback Output: the wrapped task to be posted.
308 * @return @c RetStatus handle for chaining callbacks.
309 */
310 [[nodiscard]] static RetStatus process_with_ret(const Config& config, RetCallback&& callback,
311 Callback& wrapper_callback);
312
313 private:
314 static RetStatus internal_process_with_ret(const Config& config, RetCallback&& callback, Callback& wrapper_callback);
315};
316
317} // namespace vlink
Platform-independent macro definitions for the VLink library.
#define VLINK_EXPORT
定义 macros.h:85