userver: userver/utils/periodic_task.hpp Source File
Loading...
Searching...
No Matches
periodic_task.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/periodic_task.hpp
4/// @brief @copybrief utils::PeriodicTask
5
6#include <chrono>
7#include <functional>
8#include <optional>
9#include <string>
10
11#include <userver/logging/level.hpp>
12#include <userver/utils/assert.hpp>
13#include <userver/utils/fast_pimpl.hpp>
14#include <userver/utils/flags.hpp>
15
16USERVER_NAMESPACE_BEGIN
17
18namespace engine {
19class TaskProcessor;
20} // namespace engine
21
22namespace testsuite {
23class PeriodicTaskControl;
24} // namespace testsuite
25
26namespace utils {
27
28/// @ingroup userver_concurrency
29///
30/// @brief Task that periodically runs a user callback. Callback is started
31/// after the previous callback execution is finished every `period + A - B`,
32/// where:
33/// * `A` is `+/- distribution * rand(0.0, 1.0)` if Flags::kChaotic flag is set,
34/// otherwise is `0`;
35/// * `B` is the time of previous callback execution if Flags::kStrong flag is
36/// set, otherwise is `0`;
37///
38/// TaskProcessor to execute the callback and many other options are specified
39/// in PeriodicTask::Settings.
40class PeriodicTask final {
41public:
42 enum class Flags {
43 /// None of the below flags
44 kNone = 0,
45 /// Immediately call a function
46 kNow = 1 << 0,
47 /// Account function call time as a part of wait period
48 kStrong = 1 << 1,
49 /// Randomize wait period (+-25% by default)
50 kChaotic = 1 << 2,
51 /// @deprecated Does nothing, PeriodicTask is always spawned as
52 /// `engine::Task::Importance::kCritical`.
53 /// @note Although this periodic task cannot be cancelled due to
54 /// system overload, it's cancelled upon calling `Stop`.
55 /// Subtasks that may be spawned in the callback
56 /// are not critical by default and may be cancelled as usual.
57 kCritical = 1 << 4,
58 };
59
60 /// Configuration parameters for PeriodicTask.
61 struct Settings final {
62 static constexpr uint8_t kDistributionPercent = 25;
63
64 constexpr /*implicit*/ Settings(
65 std::chrono::milliseconds period,
66 utils::Flags<Flags> flags = {},
67 logging::Level span_level = logging::Level::kInfo
68 )
69 : Settings(period, kDistributionPercent, flags, span_level)
70 {}
71
72 constexpr Settings(
73 std::chrono::milliseconds period,
74 std::chrono::milliseconds distribution,
75 utils::Flags<Flags> flags = {},
76 logging::Level span_level = logging::Level::kInfo
77 )
78 : period(period),
79 distribution(distribution),
80 flags(flags),
81 span_level(span_level)
82 {
83 UASSERT(distribution <= period);
84 }
85
86 constexpr Settings(
87 std::chrono::milliseconds period,
88 uint8_t distribution_percent,
89 utils::Flags<Flags> flags = {},
90 logging::Level span_level = logging::Level::kInfo
91 )
92 : Settings(period, period * distribution_percent / 100, flags, span_level)
93 {
94 UASSERT(distribution_percent <= 100);
95 }
96
97 template <class Rep, class Period>
98 constexpr /*implicit*/ Settings(std::chrono::duration<Rep, Period> period)
99 : Settings(period, kDistributionPercent, {}, logging::Level::kInfo)
100 {}
101
102 bool operator==(const Settings& other) const noexcept;
103 bool operator!=(const Settings& other) const noexcept;
104
105 // Note: Tidy requires us to explicitly initialize these fields, although
106 // the initializers are never used.
107
108 /// @brief Period for the task execution. Task is repeated every
109 /// `(period +/- distribution) - time of previous execution`
110 std::chrono::milliseconds period{};
111
112 /// @brief Jitter for task repetitions. If kChaotic is set in `flags`
113 /// the task is repeated every
114 /// `(period +/- distribution) - time of previous execution`
115 std::chrono::milliseconds distribution{};
116
117 /// @brief Used instead of `period` in case of exception, if set.
118 std::optional<std::chrono::milliseconds> exception_period;
119
120 /// @brief Flags that control the behavior of PeriodicTask.
121 utils::Flags<Flags> flags{};
122
123 /// @brief tracing::Span that measures each execution of the task
124 /// uses this logging level.
126
127 /// @brief TaskProcessor to execute the task. If nullptr then the
128 /// PeriodicTask::Start() calls engine::current_task::GetTaskProcessor()
129 /// to get the TaskProcessor.
130 engine::TaskProcessor* task_processor{nullptr};
131 };
132
133 /// Signature of the task to be executed each period.
134 using Callback = std::function<void()>;
135
136 /// Default constructor that does nothing.
138
139 PeriodicTask(PeriodicTask&&) = delete;
140 PeriodicTask(const PeriodicTask&) = delete;
141
142 /// Constructs the periodic task and calls Start()
143 PeriodicTask(std::string name, Settings settings, Callback callback);
144
145 /// Stops the periodic execution of previous task and starts the periodic
146 /// execution of the new task.
147 void Start(std::string name, Settings settings, Callback callback);
148
149 ~PeriodicTask();
150
151 /// @brief Stops the PeriodicTask. If a Step() is in progress, cancels it and
152 /// waits for its completion.
153 /// @warning PeriodicTask must be stopped before the callback becomes invalid.
154 /// E.g. if your class X stores PeriodicTask and the callback is class' X
155 /// method, you have to explicitly stop PeriodicTask in ~X() as after ~X()
156 /// exits the object is destroyed and using X's 'this' in callback is UB.
157 void Stop() noexcept;
158
159 /// Set all settings except flags. All flags must be set at the start.
160 void SetSettings(Settings settings);
161
162 /// @brief Non-blocking force next iteration.
163 ///
164 /// Returns immediately, without waiting for Step() to finish.
165 ///
166 /// - If PeriodicTask isn't running, then a Step() will be performed at the
167 /// start.
168 /// - If the PeriodicTask is waiting for the next iteration, then the wait is
169 /// interrupted and the next Step() is executed.
170 /// - If Step() is being executed, the current iteration will be completed and
171 /// only after that a new iteration will be called. Reason: the current
172 /// iteration is considered to be using stale data.
173 ///
174 /// @note If 'ForceStepAsync' is called multiple times while Step() is
175 /// being executed, all events will be conflated (one extra Step() call will
176 /// be executed).
178
179 /// Force next DoStep() iteration. It is guaranteed that there is at least one
180 /// call to DoStep() during SynchronizeDebug() execution. DoStep() is executed
181 /// as usual in the PeriodicTask's task (NOT in current task).
182 /// @param preserve_span run periodic task current span if true. It's here for
183 /// backward compatibility with existing tests. Will be removed in
184 /// TAXIDATA-1499.
185 /// @returns true if task was successfully executed.
186 /// @note On concurrent invocations, the task is guaranteed to be invoked
187 /// serially, one time after another.
188 bool SynchronizeDebug(bool preserve_span = false);
189
190 /// Skip Step() calls from loop until ResumeDebug() is called. If DoStep()
191 /// is executing, wait its completion, for a potentially long time.
192 /// The purpose is to control task execution from tests.
194
195 /// Stop skipping Step() calls from loop. Returns without waiting for
196 /// DoStep() call. The purpose is to control task execution from tests.
198
199 /// Checks if a periodic task (not a single iteration only) is running.
200 /// It may be in a callback execution or sleeping between callbacks.
201 bool IsRunning() const;
202
203 /// Make this periodic task available for testsuite. Testsuite provides a way
204 /// to call it directly from testcase.
205 void RegisterInTestsuite(USERVER_NAMESPACE::testsuite::PeriodicTaskControl& periodic_task_control);
206
207 /// Get current settings. Note that they might become stale very quickly.
208 Settings GetCurrentSettings() const;
209
210private:
211 class Impl;
212 constexpr static std::size_t kSize = 448;
213 constexpr static std::size_t kAlignment = 16;
214 utils::FastPimpl<Impl, kSize, kAlignment> impl_;
215};
216
217} // namespace utils
218
219USERVER_NAMESPACE_END