ESPHome 2026.7.1
Loading...
Searching...
No Matches
scheduler.h
Go to the documentation of this file.
1#pragma once
2
4#include <cstring>
5#include <string>
6#include <vector>
7#ifdef ESPHOME_THREAD_MULTI_ATOMICS
8#include <atomic>
9#endif
10
12#include "esphome/core/hal.h"
15
16namespace esphome {
17
18class Component;
19struct RetryArgs;
20
21// Forward declaration of retry_handler - needs to be non-static for friend declaration
22void retry_handler(const std::shared_ptr<RetryArgs> &args);
23
24class Scheduler {
25 // Allow retry_handler to access protected members for internal retry mechanism
26 friend void ::esphome::retry_handler(const std::shared_ptr<RetryArgs> &args);
27 // Allow DelayAction to call set_timer_common_ with skip_cancel=true for parallel script delays.
28 // This is needed to fix issue #10264 where parallel scripts with delays interfere with each other.
29 // We use friend instead of a public API because skip_cancel is dangerous - it can cause delays
30 // to accumulate and overload the scheduler if misused.
31 template<typename... Ts> friend class DelayAction;
32
33 public:
42 void set_timeout(Component *component, const char *name, uint32_t timeout, std::function<void()> &&func);
44 void set_timeout(Component *component, uint32_t id, uint32_t timeout, std::function<void()> &&func);
46 void set_timeout(Component *component, InternalSchedulerID id, uint32_t timeout, std::function<void()> &&func) {
47 this->set_timer_common_(component, SchedulerItem::TIMEOUT, NameType::NUMERIC_ID_INTERNAL, nullptr,
48 static_cast<uint32_t>(id), timeout, std::move(func));
49 }
50
51 bool cancel_timeout(Component *component, const char *name);
52 bool cancel_timeout(Component *component, uint32_t id);
53 bool cancel_timeout(Component *component, InternalSchedulerID id) {
54 return this->cancel_item_(component, NameType::NUMERIC_ID_INTERNAL, nullptr, static_cast<uint32_t>(id),
55 SchedulerItem::TIMEOUT);
56 }
57
66 void set_interval(Component *component, const char *name, uint32_t interval, std::function<void()> &&func);
68 void set_interval(Component *component, uint32_t id, uint32_t interval, std::function<void()> &&func);
70 void set_interval(Component *component, InternalSchedulerID id, uint32_t interval, std::function<void()> &&func) {
71 this->set_timer_common_(component, SchedulerItem::INTERVAL, NameType::NUMERIC_ID_INTERNAL, nullptr,
72 static_cast<uint32_t>(id), interval, std::move(func));
73 }
74
75 bool cancel_interval(Component *component, const char *name);
76 bool cancel_interval(Component *component, uint32_t id);
77 bool cancel_interval(Component *component, InternalSchedulerID id) {
78 return this->cancel_item_(component, NameType::NUMERIC_ID_INTERNAL, nullptr, static_cast<uint32_t>(id),
79 SchedulerItem::INTERVAL);
80 }
81
82 // Remove before 2026.8.0
83 ESPDEPRECATED("set_retry is deprecated and will be removed in 2026.8.0. Use set_timeout or set_interval instead.",
84 "2026.2.0")
85 void set_retry(Component *component, const std::string &name, uint32_t initial_wait_time, uint8_t max_attempts,
86 std::function<RetryResult(uint8_t)> func, float backoff_increase_factor = 1.0f);
87 // Remove before 2026.8.0
88 ESPDEPRECATED("set_retry is deprecated and will be removed in 2026.8.0. Use set_timeout or set_interval instead.",
89 "2026.2.0")
90 void set_retry(Component *component, const char *name, uint32_t initial_wait_time, uint8_t max_attempts,
91 std::function<RetryResult(uint8_t)> func, float backoff_increase_factor = 1.0f);
92 // Remove before 2026.8.0
93 ESPDEPRECATED("set_retry is deprecated and will be removed in 2026.8.0. Use set_timeout or set_interval instead.",
94 "2026.2.0")
95 void set_retry(Component *component, uint32_t id, uint32_t initial_wait_time, uint8_t max_attempts,
96 std::function<RetryResult(uint8_t)> func, float backoff_increase_factor = 1.0f);
97
98 // Remove before 2026.8.0
99 ESPDEPRECATED("cancel_retry is deprecated and will be removed in 2026.8.0.", "2026.2.0")
100 bool cancel_retry(Component *component, const std::string &name);
101 // Remove before 2026.8.0
102 ESPDEPRECATED("cancel_retry is deprecated and will be removed in 2026.8.0.", "2026.2.0")
103 bool cancel_retry(Component *component, const char *name);
104 // Remove before 2026.8.0
105 ESPDEPRECATED("cancel_retry is deprecated and will be removed in 2026.8.0.", "2026.2.0")
106 bool cancel_retry(Component *component, uint32_t id);
107
109 uint64_t millis_64() { return esphome::millis_64(); }
110
111 // Calculate when the next scheduled item should run.
112 // @param now On ESP32, unused for 64-bit extension (native); on other platforms, extended to 64-bit via rollover.
113 // Returns the time in milliseconds until the next scheduled item, or nullopt if no items.
114 // This method performs cleanup of removed items before checking the schedule.
115 // IMPORTANT: This method should only be called from the main thread (loop task).
116 optional<uint32_t> next_schedule_in(uint32_t now);
117
118 // Execute all scheduled items that are ready
119 // @param now Fresh timestamp from millis() - must not be stale/cached
120 // @return Timestamp of the last item that ran, or `now` unchanged if none ran.
121 uint32_t call(uint32_t now);
122
123 // Reclaim memory held by the post-boot peak. Frees every SchedulerItem in the
124 // recycle freelist and shrinks items_/to_add_/defer_queue_ vector capacity to
125 // their current sizes (std::vector grows by doubling and otherwise retains the
126 // peak). Live items in those vectors are preserved.
127 void trim_freelist();
128
129 // Move items from to_add_ into the main heap.
130 // IMPORTANT: This method should only be called from the main thread (loop task).
131 // Inlined: the fast path (nothing to add) is just an atomic load / empty check.
132 // The lock-free fast path uses to_add_count_ (atomic) or to_add_.empty()
133 // (single-threaded). This is safe because the main loop is the only thread
134 // that reads to_add_ without holding lock_; other threads may read it only
135 // while holding the mutex (e.g. cancel_item_locked_).
136 inline void ESPHOME_ALWAYS_INLINE HOT process_to_add() {
137 if (this->to_add_empty_())
138 return;
139 this->process_to_add_slow_path_();
140 }
141
142 // Name storage type discriminator for SchedulerItem
143 // Used to distinguish between static strings, hashed strings, numeric IDs, internal numeric IDs,
144 // and self-keyed pointers (caller-supplied `void *`, typically `this`).
145 enum class NameType : uint8_t {
146 STATIC_STRING = 0, // const char* pointer to static/flash storage
147 HASHED_STRING = 1, // uint32_t FNV-1a hash of a runtime string
148 NUMERIC_ID = 2, // uint32_t numeric identifier (component-level)
149 NUMERIC_ID_INTERNAL = 3, // uint32_t numeric identifier (core/internal, separate namespace)
150 SELF_POINTER = 4 // void* caller-supplied key (typically `this`); pointer equality
151 };
152
166 void set_timeout(const void *self, uint32_t timeout, std::function<void()> &&func);
168 void set_interval(const void *self, uint32_t interval, std::function<void()> &&func);
169 bool cancel_timeout(const void *self);
170 bool cancel_interval(const void *self);
171
172 protected:
173 struct SchedulerItem {
174 // Ordered by size to minimize padding. Mutually exclusive by state; read the component via
175 // get_component() so SELF_POINTER items read as component-less.
176 union {
177 Component *component; // live, non-SELF_POINTER: owning component
178 const LogString *source_name; // live SELF_POINTER: owning script name (log attribution)
179 SchedulerItem *next_free; // while pooled
180 };
181 // Optimized name storage using tagged union - zero heap allocation
182 union {
183 const char *static_name; // For STATIC_STRING (string literals) and SELF_POINTER (caller's `this`)
184 uint32_t hash_or_id; // For HASHED_STRING, NUMERIC_ID, and NUMERIC_ID_INTERNAL
185 } name_;
186 uint32_t interval;
187 // Split time to handle millis() rollover. The scheduler combines the 32-bit millis()
188 // with a 16-bit rollover counter to create a 48-bit time space (using 32+16 bits).
189 // This is intentionally limited to 48 bits, not stored as a full 64-bit value.
190 // With 49.7 days per 32-bit rollover, the 16-bit counter supports
191 // 49.7 days × 65536 = ~8900 years. This ensures correct scheduling
192 // even when devices run for months. Split into two fields for better memory
193 // alignment on 32-bit systems.
194 uint32_t next_execution_low_; // Lower 32 bits of execution time (millis value)
195 std::function<void()> callback;
196 uint16_t next_execution_high_; // Upper 16 bits (millis_major counter)
197
198#ifdef ESPHOME_THREAD_MULTI_ATOMICS
199 // Multi-threaded with atomics: use atomic uint8_t for lock-free access.
200 // std::atomic<bool> is not used because GCC on Xtensa generates an indirect
201 // function call for std::atomic<bool>::load() instead of inlining it.
202 // std::atomic<uint8_t> inlines correctly on all platforms.
203 std::atomic<uint8_t> remove{0};
204
205 // Bit-packed fields (5 bits used, 3 bits padding in 1 byte)
206 enum Type : uint8_t { TIMEOUT, INTERVAL } type : 1;
207 NameType name_type_ : 3; // Discriminator for name_ union (0–4, see NameType enum)
208 bool is_retry : 1; // True if this is a retry timeout
209 // 3 bits padding
210#else
211 // Single-threaded or multi-threaded without atomics: can pack all fields together
212 // Bit-packed fields (6 bits used, 2 bits padding in 1 byte)
213 enum Type : uint8_t { TIMEOUT, INTERVAL } type : 1;
214 bool remove : 1;
215 NameType name_type_ : 3; // Discriminator for name_ union (0–4, see NameType enum)
216 bool is_retry : 1; // True if this is a retry timeout
217 // 2 bits padding
218#endif
219
220 // Constructor
221 SchedulerItem()
222 : component(nullptr),
223 interval(0),
224 next_execution_low_(0),
225 next_execution_high_(0),
226#ifdef ESPHOME_THREAD_MULTI_ATOMICS
227 // remove is initialized in the member declaration
228 type(TIMEOUT),
229 name_type_(NameType::STATIC_STRING),
230 is_retry(false) {
231#else
232 type(TIMEOUT),
233 remove(false),
234 name_type_(NameType::STATIC_STRING),
235 is_retry(false) {
236#endif
237 name_.static_name = nullptr;
238 }
239
240 // Destructor - no dynamic memory to clean up (callback's std::function handles its own)
241 ~SchedulerItem() = default;
242
243 // Delete copy operations to prevent accidental copies
244 SchedulerItem(const SchedulerItem &) = delete;
245 SchedulerItem &operator=(const SchedulerItem &) = delete;
246
247 // Delete move operations: SchedulerItem objects are managed via raw pointers, never moved directly
248 SchedulerItem(SchedulerItem &&) = delete;
249 SchedulerItem &operator=(SchedulerItem &&) = delete;
250
251 // Helper to get the pointer-slot value (valid for STATIC_STRING and SELF_POINTER types).
252 // Both share the same union member, so callers (e.g. log formatters) can read either uniformly.
253 const char *get_name() const {
254 return (name_type_ == NameType::STATIC_STRING || name_type_ == NameType::SELF_POINTER) ? name_.static_name
255 : nullptr;
256 }
257
258 // Helper to get the hash or numeric ID (only valid for HASHED_STRING / NUMERIC_ID / NUMERIC_ID_INTERNAL types)
259 uint32_t get_name_hash_or_id() const {
260 return (name_type_ != NameType::STATIC_STRING && name_type_ != NameType::SELF_POINTER) ? name_.hash_or_id : 0;
261 }
262
263 // Helper to get the name type
264 NameType get_name_type() const { return name_type_; }
265
266 // Set name storage. STATIC_STRING/SELF_POINTER use the static_name pointer slot
267 // (both are pointer-width); other types use hash_or_id. Both union members occupy
268 // the same offset, so only one store is needed.
269 void set_name(NameType type, const char *static_name, uint32_t hash_or_id) {
270 if (type == NameType::STATIC_STRING || type == NameType::SELF_POINTER) {
271 name_.static_name = static_name;
272 } else {
273 name_.hash_or_id = hash_or_id;
274 }
275 name_type_ = type;
276 }
277
278 static bool cmp(SchedulerItem *a, SchedulerItem *b);
279
280 // Note: We use 48 bits total (32 + 16), stored in a 64-bit value for API compatibility.
281 // The upper 16 bits of the 64-bit value are always zero, which is fine since
282 // millis_major_ is also 16 bits and they must match.
283 constexpr uint64_t get_next_execution() const {
284 return (static_cast<uint64_t>(next_execution_high_) << 32) | next_execution_low_;
285 }
286
287 constexpr void set_next_execution(uint64_t value) {
288 next_execution_low_ = static_cast<uint32_t>(value);
289 // Cast to uint16_t intentionally truncates to lower 16 bits of the upper 32 bits.
290 // This is correct because millis_major_ that creates these values is also 16 bits.
291 next_execution_high_ = static_cast<uint16_t>(value >> 32);
292 }
293 constexpr const char *get_type_str() const { return (type == TIMEOUT) ? "timeout" : "interval"; }
294 // The owning component, or nullptr for SELF_POINTER items (whose slot holds source_name instead).
295 // All component access goes through this so SELF_POINTER items read as component-less.
296 Component *get_component() const { return name_type_ == NameType::SELF_POINTER ? nullptr : component; }
297 const LogString *get_source() const {
298 // Same no-source label as warn_blocking, for consistent log vocabulary.
299 if (name_type_ == NameType::SELF_POINTER)
300 return source_name != nullptr ? source_name : LOG_STR("a scheduled task");
301 return component != nullptr ? component->get_component_log_str() : LOG_STR("unknown");
302 }
303 };
304
305 // Common implementation for both timeout and interval
306 // name_type determines storage type: STATIC_STRING uses static_name, others use hash_or_id
307 // `source` is stored (in the union slot) only for SELF_POINTER items; ignored otherwise.
308 void set_timer_common_(Component *component, SchedulerItem::Type type, NameType name_type, const char *static_name,
309 uint32_t hash_or_id, uint32_t delay, std::function<void()> &&func, bool is_retry = false,
310 bool skip_cancel = false, const LogString *source = nullptr);
311
312 // Common implementation for retry - Remove before 2026.8.0
313 // name_type determines storage type: STATIC_STRING uses static_name, others use hash_or_id
314#pragma GCC diagnostic push
315#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
316 void set_retry_common_(Component *component, NameType name_type, const char *static_name, uint32_t hash_or_id,
317 uint32_t initial_wait_time, uint8_t max_attempts, std::function<RetryResult(uint8_t)> func,
318 float backoff_increase_factor);
319#pragma GCC diagnostic pop
320 // Common implementation for cancel_retry
321 bool cancel_retry_(Component *component, NameType name_type, const char *static_name, uint32_t hash_or_id);
322
323 // Extend a 32-bit millis() value to 64-bit. Use when the caller already has a fresh now.
324 // On platforms with native 64-bit time (ESP32, Host, Zephyr, RP2040 — see
325 // USE_NATIVE_64BIT_TIME in defines.h), ignores now and uses millis_64() directly, so the
326 // Scheduler always works in 64-bit time regardless of what the caller's 32-bit now came
327 // from. On ESP32 specifically, millis() comes from xTaskGetTickCount while millis_64()
328 // comes from esp_timer — two different clocks — but that is safe because scheduling
329 // compares millis_64 values against millis_64 only, never against millis().
330 // On platforms without native 64-bit time (e.g. ESP8266), extends now to 64-bit using
331 // rollover tracking, so both millis() and scheduling use the same underlying clock.
332 uint64_t ESPHOME_ALWAYS_INLINE millis_64_from_(uint32_t now) {
333#ifdef USE_NATIVE_64BIT_TIME
334 (void) now;
335 return millis_64();
336#else
337 return Millis64Impl::compute(now);
338#endif
339 }
340 // Cleanup logically deleted items from the scheduler
341 // Returns true if items remain after cleanup
342 // IMPORTANT: This method should only be called from the main thread (loop task).
343 // Inlined: the fast path (nothing to remove) is just an atomic load + empty check.
344 // Reading items_.empty() without the lock is safe here because only the main
345 // loop thread structurally modifies items_ (push/pop/erase). Other threads may
346 // iterate items_ and mark items removed under lock_, but never change the
347 // vector's size or data pointer.
348 inline bool ESPHOME_ALWAYS_INLINE HOT cleanup_() {
349 if (this->to_remove_empty_())
350 return !this->items_.empty();
351 return this->cleanup_slow_path_();
352 }
353 // Slow path for cleanup_() when there are items to remove - defined in scheduler.cpp
354 bool cleanup_slow_path_();
355 // Slow path for process_to_add() when there are items to merge - defined in scheduler.cpp
356 void process_to_add_slow_path_();
357 // Remove and return the front item from the heap as a raw pointer.
358 // Caller takes ownership and must either recycle or delete the item.
359 // IMPORTANT: Caller must hold the scheduler lock before calling this function.
360 SchedulerItem *pop_raw_locked_();
361 // Get or create a scheduler item from the pool
362 // IMPORTANT: Caller must hold the scheduler lock before calling this function.
363 SchedulerItem *get_item_from_pool_locked_();
364
365 private:
366 // Out-of-line helper that shrinks a SchedulerItem* vector's capacity to its current
367 // size. Centralised so trim_freelist() doesn't pay flash cost per call site.
368 void shrink_scheduler_vector_(std::vector<SchedulerItem *> *v);
369
370 // Helper to cancel matching items - must be called with lock held.
371 // When find_first=true, stops after the first match (used by set_timer_common_ where
372 // the cancel-before-add invariant guarantees at most one match).
373 // When find_first=false (default), cancels ALL matches (needed for DelayAction parallel
374 // mode where skip_cancel=true allows multiple items with the same key).
375 // name_type determines matching: STATIC_STRING uses static_name, others use hash_or_id
376 bool cancel_item_locked_(Component *component, NameType name_type, const char *static_name, uint32_t hash_or_id,
377 SchedulerItem::Type type, bool match_retry = false, bool find_first = false);
378
379 // Common implementation for cancel operations - handles locking
380 bool cancel_item_(Component *component, NameType name_type, const char *static_name, uint32_t hash_or_id,
381 SchedulerItem::Type type, bool match_retry = false);
382
383 // Helper to check if two static string names match
384 inline bool HOT names_match_static_(const char *name1, const char *name2) const {
385 // Check pointer equality first (common for static strings), then string contents
386 // The core ESPHome codebase uses static strings (const char*) for component names,
387 // making pointer comparison effective. The strcmp fallback covers distinct pointers
388 // with identical content (e.g. names built into separate static buffers).
389 return (name1 != nullptr && name2 != nullptr) && ((name1 == name2) || (strcmp(name1, name2) == 0));
390 }
391
392 // Helper function to check if item matches criteria for cancellation
393 // name_type determines matching: STATIC_STRING uses static_name, others use hash_or_id
394 // IMPORTANT: Must be called with scheduler lock held
395 inline bool HOT matches_item_locked_(SchedulerItem *item, Component *component, NameType name_type,
396 const char *static_name, uint32_t hash_or_id, SchedulerItem::Type type,
397 bool match_retry, bool skip_removed = true) const {
398 // THREAD SAFETY: Check for nullptr first to prevent LoadProhibited crashes. On multi-threaded
399 // platforms, items can be nulled in defer_queue_ during processing.
400 // Fixes: https://github.com/esphome/esphome/issues/11940
401 if (item == nullptr)
402 return false;
403 // get_component() is nullptr for SELF_POINTER items (their cancels pass nullptr too), so they
404 // match by the `this` key alone.
405 if (item->get_component() != component || item->type != type ||
406 (skip_removed && this->is_item_removed_locked_(item)) || (match_retry && !item->is_retry)) {
407 return false;
408 }
409 // Name type must match
410 if (item->get_name_type() != name_type)
411 return false;
412 // STATIC_STRING: compare string content. SELF_POINTER: raw pointer equality (no strcmp).
413 // Other types: compare hash/ID value.
414 if (name_type == NameType::STATIC_STRING) {
415 return this->names_match_static_(item->get_name(), static_name);
416 }
417 if (name_type == NameType::SELF_POINTER) {
418 return item->name_.static_name == static_name;
419 }
420 return item->get_name_hash_or_id() == hash_or_id;
421 }
422
423 // Helper to execute a scheduler item
424 uint32_t execute_item_(SchedulerItem *item, uint32_t now);
425
426 // True if the item's component is failed (so it must not run). SELF_POINTER delays have no
427 // component (get_component() == nullptr) and always fire.
428 bool is_item_failed_(SchedulerItem *item) const {
429 Component *component = item->get_component();
430 return component != nullptr && component->is_failed();
431 }
432
433 // Helper to check if item should be skipped
434 bool should_skip_item_(SchedulerItem *item) const { return is_item_removed_(item) || this->is_item_failed_(item); }
435
436 // Helper to recycle a SchedulerItem back to the pool.
437 // Takes a raw pointer — caller transfers ownership. The item is either added to the
438 // pool or deleted if the pool is full.
439 // IMPORTANT: Only call from main loop context! Recycling clears the callback,
440 // so calling from another thread while the callback is executing causes use-after-free.
441 // IMPORTANT: Caller must hold the scheduler lock before calling this function.
442 void recycle_item_main_loop_(SchedulerItem *item);
443
444 // Helper to perform full cleanup when too many items are cancelled
445 void full_cleanup_removed_items_();
446
447 // Helper to calculate random offset for interval timers - extracted to reduce code size of set_timer_common_
448 // IMPORTANT: Must not be inlined - called only for intervals, keeping it out of the hot path saves flash.
449 uint32_t __attribute__((noinline)) calculate_interval_offset_(uint32_t delay);
450
451 // Helper to check if a retry was already cancelled - extracted to reduce code size of set_timer_common_
452 // Remove before 2026.8.0 along with all retry code.
453 // IMPORTANT: Must not be inlined - retry path is cold and deprecated.
454 // IMPORTANT: Caller must hold the scheduler lock before calling this function.
455 bool __attribute__((noinline))
456 is_retry_cancelled_locked_(Component *component, NameType name_type, const char *static_name, uint32_t hash_or_id);
457
458#ifdef ESPHOME_DEBUG_SCHEDULER
459 // Helper for debug logging in set_timer_common_ - extracted to reduce code size
460 void debug_log_timer_(const SchedulerItem *item, NameType name_type, const char *static_name, uint32_t hash_or_id,
461 SchedulerItem::Type type, uint32_t delay, uint64_t now);
462#endif /* ESPHOME_DEBUG_SCHEDULER */
463
464#ifndef ESPHOME_THREAD_SINGLE
465 // Process defer queue for FIFO execution of deferred items.
466 // IMPORTANT: This method should only be called from the main thread (loop task).
467 // Inlined: the fast path (nothing deferred) is just an atomic load check.
468 inline void ESPHOME_ALWAYS_INLINE HOT process_defer_queue_(uint32_t &now) {
469 // Fast path: nothing to process, avoid lock entirely.
470 // Worst case is a one-loop-iteration delay before newly deferred items are processed.
471 if (this->defer_empty_())
472 return;
473 this->process_defer_queue_slow_path_(now);
474 }
475
476 // Slow path for process_defer_queue_() - defined in scheduler.cpp
477 void process_defer_queue_slow_path_(uint32_t &now);
478
479 // Helper to cleanup defer_queue_ after processing.
480 // Keeps the common clear() path inline, outlines the rare compaction to keep
481 // cold code out of the hot instruction cache lines.
482 // IMPORTANT: Caller must hold the scheduler lock before calling this function.
483 inline void cleanup_defer_queue_locked_() {
484 // Check if new items were added by producers during processing
485 if (this->defer_queue_front_ >= this->defer_queue_.size()) {
486 // Common case: no new items - clear everything
487 this->defer_queue_.clear();
488 } else {
489 // Rare case: new items were added during processing - outlined to keep cold code
490 // out of the hot instruction cache lines
491 this->compact_defer_queue_locked_();
492 }
493 this->defer_queue_front_ = 0;
494 }
495
496 // Cold path for compacting defer_queue_ when new items were added during processing.
497 // IMPORTANT: Caller must hold the scheduler lock before calling this function.
498 // IMPORTANT: Must not be inlined - rare path, outlined to keep it out of the hot instruction cache lines.
499 void __attribute__((noinline)) compact_defer_queue_locked_();
500#endif /* not ESPHOME_THREAD_SINGLE */
501
502 // Helper to check if item is marked for removal (platform-specific)
503 // Returns true if item should be skipped, handles platform-specific synchronization
504 // For ESPHOME_THREAD_MULTI_NO_ATOMICS platforms, the caller must hold the scheduler lock before calling this
505 // function.
506 bool is_item_removed_(SchedulerItem *item) const {
507#ifdef ESPHOME_THREAD_MULTI_ATOMICS
508 // Multi-threaded with atomics: use atomic load for lock-free access
509 return item->remove.load(std::memory_order_acquire);
510#else
511 // Single-threaded (ESPHOME_THREAD_SINGLE) or
512 // multi-threaded without atomics (ESPHOME_THREAD_MULTI_NO_ATOMICS): direct read
513 // For ESPHOME_THREAD_MULTI_NO_ATOMICS, caller MUST hold lock!
514 return item->remove;
515#endif
516 }
517
518 // Helper to check if item is marked for removal when lock is already held.
519 // Uses relaxed ordering since the mutex provides all necessary synchronization.
520 // IMPORTANT: Caller must hold the scheduler lock before calling this function.
521 bool is_item_removed_locked_(SchedulerItem *item) const {
522#ifdef ESPHOME_THREAD_MULTI_ATOMICS
523 // Lock already held - relaxed is sufficient, mutex provides ordering
524 return item->remove.load(std::memory_order_relaxed);
525#else
526 return item->remove;
527#endif
528 }
529
530 // Helper to set item removal flag (platform-specific)
531 // For ESPHOME_THREAD_MULTI_NO_ATOMICS platforms, the caller must hold the scheduler lock before calling this
532 // function. Uses memory_order_release when setting to true (for cancellation synchronization),
533 // and memory_order_relaxed when setting to false (for initialization).
534 void set_item_removed_(SchedulerItem *item, bool removed) {
535#ifdef ESPHOME_THREAD_MULTI_ATOMICS
536 // Multi-threaded with atomics: use atomic store with appropriate ordering
537 // Release ordering when setting to true ensures cancellation is visible to other threads
538 // Relaxed ordering when setting to false is sufficient for initialization
539 item->remove.store(removed ? 1 : 0, removed ? std::memory_order_release : std::memory_order_relaxed);
540#else
541 // Single-threaded (ESPHOME_THREAD_SINGLE) or
542 // multi-threaded without atomics (ESPHOME_THREAD_MULTI_NO_ATOMICS): direct write
543 // For ESPHOME_THREAD_MULTI_NO_ATOMICS, caller MUST hold lock!
544 item->remove = removed;
545#endif
546 }
547
548 // Helper to mark matching items in a container as removed.
549 // When find_first=true, stops after the first match (used by set_timer_common_ where
550 // the cancel-before-add invariant guarantees at most one match).
551 // When find_first=false, marks ALL matches (needed for public cancel path where
552 // DelayAction parallel mode with skip_cancel=true can create multiple items with the same key).
553 // name_type determines matching: STATIC_STRING uses static_name, others use hash_or_id
554 // Returns the number of items marked for removal.
555 // IMPORTANT: Must be called with scheduler lock held
556 // Inlined: the fast path (empty container) avoids calling the out-of-line scan.
557 inline size_t HOT mark_matching_items_removed_locked_(std::vector<SchedulerItem *> &container, Component *component,
558 NameType name_type, const char *static_name,
559 uint32_t hash_or_id, SchedulerItem::Type type, bool match_retry,
560 bool find_first = false) {
561 if (container.empty())
562 return 0;
563 return this->mark_matching_items_removed_slow_locked_(container, component, name_type, static_name, hash_or_id,
564 type, match_retry, find_first);
565 }
566
567 // Out-of-line slow path for mark_matching_items_removed_locked_ when container is non-empty.
568 // IMPORTANT: Must be called with scheduler lock held
569 __attribute__((noinline)) size_t mark_matching_items_removed_slow_locked_(
570 std::vector<SchedulerItem *> &container, Component *component, NameType name_type, const char *static_name,
571 uint32_t hash_or_id, SchedulerItem::Type type, bool match_retry, bool find_first);
572
573 Mutex lock_;
574 std::vector<SchedulerItem *> items_;
575 std::vector<SchedulerItem *> to_add_;
576
577#ifndef ESPHOME_THREAD_SINGLE
578 // Fast-path counter for process_to_add() to skip taking the lock when there
579 // is nothing to add. std::atomic on ATOMICS; plain uint32_t on NO_ATOMICS
580 // (BK72xx — ARMv5TE single-core, lacks LDREX/STREX so std::atomic RMW would
581 // require libatomic). Reads use __atomic_load_n(__ATOMIC_RELAXED) on
582 // NO_ATOMICS — compiles to a plain LDR (aligned 32-bit load is naturally
583 // atomic on ARMv5TE) but expresses the concurrent-access intent in the C++
584 // memory model. Writes live behind *_locked_ helpers and must hold lock_.
585#ifdef ESPHOME_THREAD_MULTI_ATOMICS
586 std::atomic<uint32_t> to_add_count_{0};
587#else
588 uint32_t to_add_count_{0};
589#endif
590#endif /* ESPHOME_THREAD_SINGLE */
591
592 // Fast-path helper for process_to_add() to decide if it can skip the lock.
593 bool to_add_empty_() const {
594#ifdef ESPHOME_THREAD_SINGLE
595 return this->to_add_.empty();
596#elif defined(ESPHOME_THREAD_MULTI_ATOMICS)
597 return this->to_add_count_.load(std::memory_order_relaxed) == 0;
598#else
599 return __atomic_load_n(&this->to_add_count_, __ATOMIC_RELAXED) == 0;
600#endif
601 }
602
603 // Increment to_add_count_ (no-op on single-threaded platforms).
604 // On NO_ATOMICS the caller must hold lock_; both load and store go through
605 // __atomic_*_n with __ATOMIC_RELAXED to keep every access to the counter
606 // explicitly atomic in the C++ memory model (same ARMv5TE codegen as
607 // plain LDR+STR).
608 void to_add_count_increment_locked_() {
609#if defined(ESPHOME_THREAD_SINGLE)
610 // No counter needed — to_add_empty_() checks the vector directly
611#elif defined(ESPHOME_THREAD_MULTI_ATOMICS)
612 this->to_add_count_.fetch_add(1, std::memory_order_relaxed);
613#else
614 uint32_t v = __atomic_load_n(&this->to_add_count_, __ATOMIC_RELAXED);
615 __atomic_store_n(&this->to_add_count_, v + 1, __ATOMIC_RELAXED);
616#endif
617 }
618
619 // Reset to_add_count_ (no-op on single-threaded platforms)
620 void to_add_count_clear_locked_() {
621#if defined(ESPHOME_THREAD_SINGLE)
622 // No counter needed — to_add_empty_() checks the vector directly
623#elif defined(ESPHOME_THREAD_MULTI_ATOMICS)
624 this->to_add_count_.store(0, std::memory_order_relaxed);
625#else
626 __atomic_store_n(&this->to_add_count_, 0, __ATOMIC_RELAXED);
627#endif
628 }
629
630#ifndef ESPHOME_THREAD_SINGLE
631 // Single-core platforms don't need the defer queue and save ~32 bytes of RAM
632 // Using std::vector instead of std::deque avoids 512-byte chunked allocations
633 // Index tracking avoids O(n) erase() calls when draining the queue each loop
634 std::vector<SchedulerItem *> defer_queue_; // FIFO queue for defer() calls
635 size_t defer_queue_front_{0}; // Index of first valid item in defer_queue_ (tracks consumed items)
636
637 // Fast-path counter for process_defer_queue_() to skip lock when nothing to
638 // process. See to_add_count_ above for the NO_ATOMICS rationale.
639#ifdef ESPHOME_THREAD_MULTI_ATOMICS
640 std::atomic<uint32_t> defer_count_{0};
641#else
642 uint32_t defer_count_{0};
643#endif
644
645 bool defer_empty_() const {
646 // defer_queue_ only exists on multi-threaded platforms, so no ESPHOME_THREAD_SINGLE path
647#ifdef ESPHOME_THREAD_MULTI_ATOMICS
648 return this->defer_count_.load(std::memory_order_relaxed) == 0;
649#else
650 return __atomic_load_n(&this->defer_count_, __ATOMIC_RELAXED) == 0;
651#endif
652 }
653
654 void defer_count_increment_locked_() {
655#ifdef ESPHOME_THREAD_MULTI_ATOMICS
656 this->defer_count_.fetch_add(1, std::memory_order_relaxed);
657#else
658 uint32_t v = __atomic_load_n(&this->defer_count_, __ATOMIC_RELAXED);
659 __atomic_store_n(&this->defer_count_, v + 1, __ATOMIC_RELAXED);
660#endif
661 }
662
663 void defer_count_clear_locked_() {
664#ifdef ESPHOME_THREAD_MULTI_ATOMICS
665 this->defer_count_.store(0, std::memory_order_relaxed);
666#else
667 __atomic_store_n(&this->defer_count_, 0, __ATOMIC_RELAXED);
668#endif
669 }
670
671#endif /* ESPHOME_THREAD_SINGLE */
672
673 // Counter for items marked for removal. Incremented cross-thread in
674 // cancel_item_locked_(). See to_add_count_ above for the NO_ATOMICS
675 // rationale.
676#ifdef ESPHOME_THREAD_MULTI_ATOMICS
677 std::atomic<uint32_t> to_remove_{0};
678#else
679 uint32_t to_remove_{0};
680#endif
681
682 // Lock-free check if there are items to remove (for fast-path in cleanup_)
683 bool to_remove_empty_() const {
684#if defined(ESPHOME_THREAD_MULTI_ATOMICS)
685 return this->to_remove_.load(std::memory_order_relaxed) == 0;
686#elif defined(ESPHOME_THREAD_MULTI_NO_ATOMICS)
687 return __atomic_load_n(&this->to_remove_, __ATOMIC_RELAXED) == 0;
688#else
689 return this->to_remove_ == 0;
690#endif
691 }
692
693 void to_remove_add_locked_(uint32_t count) {
694#if defined(ESPHOME_THREAD_MULTI_ATOMICS)
695 this->to_remove_.fetch_add(count, std::memory_order_relaxed);
696#elif defined(ESPHOME_THREAD_MULTI_NO_ATOMICS)
697 uint32_t v = __atomic_load_n(&this->to_remove_, __ATOMIC_RELAXED);
698 __atomic_store_n(&this->to_remove_, v + count, __ATOMIC_RELAXED);
699#else
700 this->to_remove_ += count;
701#endif
702 }
703
704 void to_remove_decrement_locked_() {
705#if defined(ESPHOME_THREAD_MULTI_ATOMICS)
706 this->to_remove_.fetch_sub(1, std::memory_order_relaxed);
707#elif defined(ESPHOME_THREAD_MULTI_NO_ATOMICS)
708 uint32_t v = __atomic_load_n(&this->to_remove_, __ATOMIC_RELAXED);
709 __atomic_store_n(&this->to_remove_, v - 1, __ATOMIC_RELAXED);
710#else
711 this->to_remove_--;
712#endif
713 }
714
715 void to_remove_clear_locked_() {
716#if defined(ESPHOME_THREAD_MULTI_ATOMICS)
717 this->to_remove_.store(0, std::memory_order_relaxed);
718#elif defined(ESPHOME_THREAD_MULTI_NO_ATOMICS)
719 __atomic_store_n(&this->to_remove_, 0, __ATOMIC_RELAXED);
720#else
721 this->to_remove_ = 0;
722#endif
723 }
724
725 uint32_t to_remove_count_() const {
726#if defined(ESPHOME_THREAD_MULTI_ATOMICS)
727 return this->to_remove_.load(std::memory_order_relaxed);
728#elif defined(ESPHOME_THREAD_MULTI_NO_ATOMICS)
729 return __atomic_load_n(&this->to_remove_, __ATOMIC_RELAXED);
730#else
731 return this->to_remove_;
732#endif
733 }
734
735 // Intrusive freelist threaded through SchedulerItem::next_free. Unbounded so it quiesces at the
736 // app's concurrent-timer high-water mark; the previous fixed cap caused steady-state new/delete
737 // churn on devices with many timers (see https://github.com/esphome/backlog/issues/52).
738 SchedulerItem *scheduler_item_pool_head_{nullptr};
739 size_t scheduler_item_pool_size_{0};
740
741#ifdef ESPHOME_DEBUG_SCHEDULER
742 // Leak detection: tracks total live SchedulerItem allocations.
743 // Invariant: debug_live_items_ == items_.size() + to_add_.size() + defer_queue_.size() + scheduler_item_pool_size_
744 // Verified periodically in call() to catch leaks early.
745 size_t debug_live_items_{0};
746
747 // Verify the scheduler memory invariant: all allocated items are accounted for.
748 // Returns true if no leak detected. Logs an error and asserts on failure.
749 bool debug_verify_no_leak_() const;
750#endif
751};
752
753} // namespace esphome
struct @65::@66 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Definition main_task.h:32
const Component * component
Definition component.cpp:34
void delay(unsigned long ms)
uint16_t type
uint8_t source_name[64]
void retry_handler(const std::shared_ptr< RetryArgs > &args)
const char int const __FlashStringHelper va_list args
Definition log.h:74
uint64_t millis_64()
Definition hal.cpp:29
STL namespace.
static void uint32_t