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