ESPHome 2026.4.0
Loading...
Searching...
No Matches
scheduler.cpp
Go to the documentation of this file.
1#include "scheduler.h"
2
3#include "application.h"
5#include "esphome/core/hal.h"
7#include "esphome/core/log.h"
9#include <algorithm>
10#include <cinttypes>
11#include <cstring>
12
13namespace esphome {
14
15static const char *const TAG = "scheduler";
16
17// Memory pool configuration constants
18// Pool size of 5 matches typical usage patterns (2-4 active timers)
19// - Minimal memory overhead (~250 bytes on ESP32)
20// - Sufficient for most configs with a couple sensors/components
21// - Still prevents heap fragmentation and allocation stalls
22// - Complex setups with many timers will just allocate beyond the pool
23// See https://github.com/esphome/backlog/issues/52
24static constexpr size_t MAX_POOL_SIZE = 5;
25
26// Maximum number of logically deleted (cancelled) items before forcing cleanup.
27// Set to 5 to match the pool size - when we have as many cancelled items as our
28// pool can hold, it's time to clean up and recycle them.
29static constexpr uint32_t MAX_LOGICALLY_DELETED_ITEMS = 5;
30// max delay to start an interval sequence
31static constexpr uint32_t MAX_INTERVAL_DELAY = 5000;
32
33#if defined(ESPHOME_LOG_HAS_VERBOSE) || defined(ESPHOME_DEBUG_SCHEDULER)
34// Helper struct for formatting scheduler item names consistently in logs
35// Uses a stack buffer to avoid heap allocation
36// Uses ESPHOME_snprintf_P/ESPHOME_PSTR for ESP8266 to keep format strings in flash
37struct SchedulerNameLog {
38 char buffer[20]; // Enough for "id:4294967295" or "hash:0xFFFFFFFF" or "(null)"
39
40 // Format a scheduler item name for logging
41 // Returns pointer to formatted string (either static_name or internal buffer)
42 const char *format(Scheduler::NameType name_type, const char *static_name, uint32_t hash_or_id) {
43 using NameType = Scheduler::NameType;
44 if (name_type == NameType::STATIC_STRING) {
45 if (static_name)
46 return static_name;
47 // Copy "(null)" to buffer to keep it in flash on ESP8266
48 ESPHOME_strncpy_P(buffer, ESPHOME_PSTR("(null)"), sizeof(buffer));
49 return buffer;
50 } else if (name_type == NameType::HASHED_STRING) {
51 ESPHOME_snprintf_P(buffer, sizeof(buffer), ESPHOME_PSTR("hash:0x%08" PRIX32), hash_or_id);
52 return buffer;
53 } else if (name_type == NameType::NUMERIC_ID) {
54 ESPHOME_snprintf_P(buffer, sizeof(buffer), ESPHOME_PSTR("id:%" PRIu32), hash_or_id);
55 return buffer;
56 } else { // NUMERIC_ID_INTERNAL
57 ESPHOME_snprintf_P(buffer, sizeof(buffer), ESPHOME_PSTR("iid:%" PRIu32), hash_or_id);
58 return buffer;
59 }
60 }
61};
62#endif
63
64// Uncomment to debug scheduler
65// #define ESPHOME_DEBUG_SCHEDULER
66
67#ifdef ESPHOME_DEBUG_SCHEDULER
68// Helper to validate that a pointer looks like it's in static memory
69static void validate_static_string(const char *name) {
70 if (name == nullptr)
71 return;
72
73 // This is a heuristic check - stack and heap pointers are typically
74 // much higher in memory than static data
75 uintptr_t addr = reinterpret_cast<uintptr_t>(name);
76
77 // Create a stack variable to compare against
78 int stack_var;
79 uintptr_t stack_addr = reinterpret_cast<uintptr_t>(&stack_var);
80
81 // If the string pointer is near our stack variable, it's likely on the stack
82 // Using 8KB range as ESP32 main task stack is typically 8192 bytes
83 if (addr > (stack_addr - 0x2000) && addr < (stack_addr + 0x2000)) {
84 ESP_LOGW(TAG,
85 "WARNING: Scheduler name '%s' at %p appears to be on the stack - this is unsafe!\n"
86 " Stack reference at %p",
87 name, name, &stack_var);
88 }
89
90 // Also check if it might be on the heap by seeing if it's in a very different range
91 // This is platform-specific but generally heap is allocated far from static memory
92 static const char *static_str = "test";
93 uintptr_t static_addr = reinterpret_cast<uintptr_t>(static_str);
94
95 // If the address is very far from known static memory, it might be heap
96 if (addr > static_addr + 0x100000 || (static_addr > 0x100000 && addr < static_addr - 0x100000)) {
97 ESP_LOGW(TAG, "WARNING: Scheduler name '%s' at %p might be on heap (static ref at %p)", name, name, static_str);
98 }
99}
100#endif /* ESPHOME_DEBUG_SCHEDULER */
101
102// A note on locking: the `lock_` lock protects the `items_` and `to_add_` containers. It must be taken when writing to
103// them (i.e. when adding/removing items, but not when changing items). As items are only deleted from the loop task,
104// iterating over them from the loop task is fine; but iterating from any other context requires the lock to be held to
105// avoid the main thread modifying the list while it is being accessed.
106
107// Calculate random offset for interval timers
108// Extracted from set_timer_common_ to reduce code size - only needed for intervals, not timeouts
109uint32_t Scheduler::calculate_interval_offset_(uint32_t delay) {
110 uint32_t max_offset = std::min(delay / 2, MAX_INTERVAL_DELAY);
111 // Multiply-and-shift: uniform random in [0, max_offset) without floating point
112 return static_cast<uint32_t>((static_cast<uint64_t>(random_uint32()) * max_offset) >> 32);
113}
114
115// Check if a retry was already cancelled in items_ or to_add_
116// Extracted from set_timer_common_ to reduce code size - retry path is cold and deprecated
117// Remove before 2026.8.0 along with all retry code
118bool Scheduler::is_retry_cancelled_locked_(Component *component, NameType name_type, const char *static_name,
119 uint32_t hash_or_id) {
120 for (auto *container : {&this->items_, &this->to_add_}) {
121 for (auto *item : *container) {
122 if (item != nullptr && this->is_item_removed_locked_(item) &&
123 this->matches_item_locked_(item, component, name_type, static_name, hash_or_id, SchedulerItem::TIMEOUT,
124 /* match_retry= */ true, /* skip_removed= */ false)) {
125 return true;
126 }
127 }
128 }
129 return false;
130}
131
132// Common implementation for both timeout and interval
133// name_type determines storage type: STATIC_STRING uses static_name, others use hash_or_id
134void HOT Scheduler::set_timer_common_(Component *component, SchedulerItem::Type type, NameType name_type,
135 const char *static_name, uint32_t hash_or_id, uint32_t delay,
136 std::function<void()> &&func, bool is_retry, bool skip_cancel) {
137 if (delay == SCHEDULER_DONT_RUN) {
138 // Still need to cancel existing timer if we have a name/id
139 if (!skip_cancel) {
140 LockGuard guard{this->lock_};
141 this->cancel_item_locked_(component, name_type, static_name, hash_or_id, type, /* match_retry= */ false,
142 /* find_first= */ true);
143 }
144 return;
145 }
146
147 // Take lock early to protect scheduler_item_pool_ access and retry-cancelled check
148 LockGuard guard{this->lock_};
149
150 // For retries, check if there's a cancelled timeout first - before allocating an item.
151 // Skip check for anonymous retries (STATIC_STRING with nullptr) - they can't be cancelled by name
152 // Skip check for defer (delay=0) - deferred retries bypass the cancellation check
153 if (is_retry && delay != 0 && (name_type != NameType::STATIC_STRING || static_name != nullptr) &&
154 type == SchedulerItem::TIMEOUT &&
155 this->is_retry_cancelled_locked_(component, name_type, static_name, hash_or_id)) {
156#ifdef ESPHOME_DEBUG_SCHEDULER
157 SchedulerNameLog skip_name_log;
158 ESP_LOGD(TAG, "Skipping retry '%s' - found cancelled item",
159 skip_name_log.format(name_type, static_name, hash_or_id));
160#endif
161 return;
162 }
163
164 // Create and populate the scheduler item
165 SchedulerItem *item = this->get_item_from_pool_locked_();
166 item->component = component;
167 item->set_name(name_type, static_name, hash_or_id);
168 item->type = type;
169 // Use destroy + placement-new instead of move-assignment.
170 // GCC's std::function::operator=(function&&) does a full swap dance even when the
171 // target is empty. Since recycled/new items always have an empty callback, we can
172 // destroy the empty one (no-op) and move-construct directly, saving ~40 bytes of
173 // swap/destructor code on Xtensa.
174 item->callback.~function();
175 new (&item->callback) std::function<void()>(std::move(func));
176 // Reset remove flag - recycled items may have been cancelled (remove=true) in previous use
177 this->set_item_removed_(item, false);
178 item->is_retry = is_retry;
179
180 // Determine target container: defer_queue_ for deferred items, to_add_ for everything else.
181 // Using a pointer lets both paths share the cancel + push_back epilogue.
182 auto *target = &this->to_add_;
183
184#ifndef ESPHOME_THREAD_SINGLE
185 // Special handling for defer() (delay = 0, type = TIMEOUT)
186 // Single-core platforms don't need thread-safe defer handling
187 if (delay == 0 && type == SchedulerItem::TIMEOUT) {
188 // Put in defer queue for guaranteed FIFO execution
189 target = &this->defer_queue_;
190 } else
191#endif /* not ESPHOME_THREAD_SINGLE */
192 {
193 // Only non-defer items need a timestamp for scheduling
194 const uint64_t now_64 = millis_64();
195
196 // Type-specific setup
197 if (type == SchedulerItem::INTERVAL) {
198 item->interval = delay;
199 // first execution happens immediately after a random smallish offset
200 uint32_t offset = this->calculate_interval_offset_(delay);
201 item->set_next_execution(now_64 + offset);
202#ifdef ESPHOME_LOG_HAS_VERBOSE
203 SchedulerNameLog name_log;
204 ESP_LOGV(TAG, "Scheduler interval for %s is %" PRIu32 "ms, offset %" PRIu32 "ms",
205 name_log.format(name_type, static_name, hash_or_id), delay, offset);
206#endif
207 } else {
208 item->interval = 0;
209 item->set_next_execution(now_64 + delay);
210 }
211
212#ifdef ESPHOME_DEBUG_SCHEDULER
213 this->debug_log_timer_(item, name_type, static_name, hash_or_id, type, delay, now_64);
214#endif /* ESPHOME_DEBUG_SCHEDULER */
215 }
216
217 // Common epilogue: atomic cancel-and-add (unless skip_cancel is true or anonymous)
218 // Anonymous items (STATIC_STRING with nullptr) can never match anything, so skip the scan.
219 if (!skip_cancel && (name_type != NameType::STATIC_STRING || static_name != nullptr)) {
220 this->cancel_item_locked_(component, name_type, static_name, hash_or_id, type, /* match_retry= */ false,
221 /* find_first= */ true);
222 }
223 target->push_back(item);
224 if (target == &this->to_add_) {
225 this->to_add_count_increment_();
226 }
227#ifndef ESPHOME_THREAD_SINGLE
228 else {
229 this->defer_count_increment_();
230 }
231#endif
232}
233
234void HOT Scheduler::set_timeout(Component *component, const char *name, uint32_t timeout,
235 std::function<void()> &&func) {
236 this->set_timer_common_(component, SchedulerItem::TIMEOUT, NameType::STATIC_STRING, name, 0, timeout,
237 std::move(func));
238}
239
240void HOT Scheduler::set_timeout(Component *component, const std::string &name, uint32_t timeout,
241 std::function<void()> &&func) {
242 this->set_timer_common_(component, SchedulerItem::TIMEOUT, NameType::HASHED_STRING, nullptr, fnv1a_hash(name),
243 timeout, std::move(func));
244}
245void HOT Scheduler::set_timeout(Component *component, uint32_t id, uint32_t timeout, std::function<void()> &&func) {
246 this->set_timer_common_(component, SchedulerItem::TIMEOUT, NameType::NUMERIC_ID, nullptr, id, timeout,
247 std::move(func));
248}
249bool HOT Scheduler::cancel_timeout(Component *component, const std::string &name) {
250 return this->cancel_item_(component, NameType::HASHED_STRING, nullptr, fnv1a_hash(name), SchedulerItem::TIMEOUT);
251}
252bool HOT Scheduler::cancel_timeout(Component *component, const char *name) {
253 return this->cancel_item_(component, NameType::STATIC_STRING, name, 0, SchedulerItem::TIMEOUT);
254}
255bool HOT Scheduler::cancel_timeout(Component *component, uint32_t id) {
256 return this->cancel_item_(component, NameType::NUMERIC_ID, nullptr, id, SchedulerItem::TIMEOUT);
257}
258void HOT Scheduler::set_interval(Component *component, const std::string &name, uint32_t interval,
259 std::function<void()> &&func) {
260 this->set_timer_common_(component, SchedulerItem::INTERVAL, NameType::HASHED_STRING, nullptr, fnv1a_hash(name),
261 interval, std::move(func));
262}
263
264void HOT Scheduler::set_interval(Component *component, const char *name, uint32_t interval,
265 std::function<void()> &&func) {
266 this->set_timer_common_(component, SchedulerItem::INTERVAL, NameType::STATIC_STRING, name, 0, interval,
267 std::move(func));
268}
269void HOT Scheduler::set_interval(Component *component, uint32_t id, uint32_t interval, std::function<void()> &&func) {
270 this->set_timer_common_(component, SchedulerItem::INTERVAL, NameType::NUMERIC_ID, nullptr, id, interval,
271 std::move(func));
272}
273bool HOT Scheduler::cancel_interval(Component *component, const std::string &name) {
274 return this->cancel_item_(component, NameType::HASHED_STRING, nullptr, fnv1a_hash(name), SchedulerItem::INTERVAL);
275}
276bool HOT Scheduler::cancel_interval(Component *component, const char *name) {
277 return this->cancel_item_(component, NameType::STATIC_STRING, name, 0, SchedulerItem::INTERVAL);
278}
279bool HOT Scheduler::cancel_interval(Component *component, uint32_t id) {
280 return this->cancel_item_(component, NameType::NUMERIC_ID, nullptr, id, SchedulerItem::INTERVAL);
281}
282
283// Suppress deprecation warnings for RetryResult usage in the still-present (but deprecated) retry implementation.
284// Remove before 2026.8.0 along with all retry code.
285#pragma GCC diagnostic push
286#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
287
288struct RetryArgs {
289 // Ordered to minimize padding on 32-bit systems
290 std::function<RetryResult(uint8_t)> func;
291 Component *component;
292 Scheduler *scheduler;
293 // Union for name storage - only one is used based on name_type
294 union {
295 const char *static_name; // For STATIC_STRING
296 uint32_t hash_or_id; // For HASHED_STRING or NUMERIC_ID
297 } name_;
298 uint32_t current_interval;
299 float backoff_increase_factor;
300 Scheduler::NameType name_type; // Discriminator for name_ union
301 uint8_t retry_countdown;
302};
303
304void retry_handler(const std::shared_ptr<RetryArgs> &args) {
305 RetryResult const retry_result = args->func(--args->retry_countdown);
306 if (retry_result == RetryResult::DONE || args->retry_countdown <= 0)
307 return;
308 // second execution of `func` happens after `initial_wait_time`
309 // args->name_ is owned by the shared_ptr<RetryArgs>
310 // which is captured in the lambda and outlives the SchedulerItem
311 const char *static_name = (args->name_type == Scheduler::NameType::STATIC_STRING) ? args->name_.static_name : nullptr;
312 uint32_t hash_or_id = (args->name_type != Scheduler::NameType::STATIC_STRING) ? args->name_.hash_or_id : 0;
313 args->scheduler->set_timer_common_(
314 args->component, Scheduler::SchedulerItem::TIMEOUT, args->name_type, static_name, hash_or_id,
315 args->current_interval, [args]() { retry_handler(args); },
316 /* is_retry= */ true);
317 // backoff_increase_factor applied to third & later executions
318 args->current_interval *= args->backoff_increase_factor;
319}
320
321void HOT Scheduler::set_retry_common_(Component *component, NameType name_type, const char *static_name,
322 uint32_t hash_or_id, uint32_t initial_wait_time, uint8_t max_attempts,
323 std::function<RetryResult(uint8_t)> func, float backoff_increase_factor) {
324 this->cancel_retry_(component, name_type, static_name, hash_or_id);
325
326 if (initial_wait_time == SCHEDULER_DONT_RUN)
327 return;
328
329#ifdef ESPHOME_LOG_HAS_VERY_VERBOSE
330 {
331 SchedulerNameLog name_log;
332 ESP_LOGVV(TAG, "set_retry(name='%s', initial_wait_time=%" PRIu32 ", max_attempts=%u, backoff_factor=%0.1f)",
333 name_log.format(name_type, static_name, hash_or_id), initial_wait_time, max_attempts,
334 backoff_increase_factor);
335 }
336#endif
337
338 if (backoff_increase_factor < 0.0001) {
339 ESP_LOGE(TAG, "set_retry: backoff_factor %0.1f too small, using 1.0: %s", backoff_increase_factor,
340 (name_type == NameType::STATIC_STRING && static_name) ? static_name : "");
341 backoff_increase_factor = 1;
342 }
343
344 auto args = std::make_shared<RetryArgs>();
345 args->func = std::move(func);
346 args->component = component;
347 args->scheduler = this;
348 args->name_type = name_type;
349 if (name_type == NameType::STATIC_STRING) {
350 args->name_.static_name = static_name;
351 } else {
352 args->name_.hash_or_id = hash_or_id;
353 }
354 args->current_interval = initial_wait_time;
355 args->backoff_increase_factor = backoff_increase_factor;
356 args->retry_countdown = max_attempts;
357
358 // First execution of `func` immediately - use set_timer_common_ with is_retry=true
359 this->set_timer_common_(
360 component, SchedulerItem::TIMEOUT, name_type, static_name, hash_or_id, 0, [args]() { retry_handler(args); },
361 /* is_retry= */ true);
362}
363
364void HOT Scheduler::set_retry(Component *component, const char *name, uint32_t initial_wait_time, uint8_t max_attempts,
365 std::function<RetryResult(uint8_t)> func, float backoff_increase_factor) {
366 this->set_retry_common_(component, NameType::STATIC_STRING, name, 0, initial_wait_time, max_attempts, std::move(func),
367 backoff_increase_factor);
368}
369
370bool HOT Scheduler::cancel_retry_(Component *component, NameType name_type, const char *static_name,
371 uint32_t hash_or_id) {
372 return this->cancel_item_(component, name_type, static_name, hash_or_id, SchedulerItem::TIMEOUT,
373 /* match_retry= */ true);
374}
375bool HOT Scheduler::cancel_retry(Component *component, const char *name) {
376 return this->cancel_retry_(component, NameType::STATIC_STRING, name, 0);
377}
378
379void HOT Scheduler::set_retry(Component *component, const std::string &name, uint32_t initial_wait_time,
380 uint8_t max_attempts, std::function<RetryResult(uint8_t)> func,
381 float backoff_increase_factor) {
382 this->set_retry_common_(component, NameType::HASHED_STRING, nullptr, fnv1a_hash(name), initial_wait_time,
383 max_attempts, std::move(func), backoff_increase_factor);
384}
385
386bool HOT Scheduler::cancel_retry(Component *component, const std::string &name) {
387 return this->cancel_retry_(component, NameType::HASHED_STRING, nullptr, fnv1a_hash(name));
388}
389
390void HOT Scheduler::set_retry(Component *component, uint32_t id, uint32_t initial_wait_time, uint8_t max_attempts,
391 std::function<RetryResult(uint8_t)> func, float backoff_increase_factor) {
392 this->set_retry_common_(component, NameType::NUMERIC_ID, nullptr, id, initial_wait_time, max_attempts,
393 std::move(func), backoff_increase_factor);
394}
395
396bool HOT Scheduler::cancel_retry(Component *component, uint32_t id) {
397 return this->cancel_retry_(component, NameType::NUMERIC_ID, nullptr, id);
398}
399
400#pragma GCC diagnostic pop // End suppression of deprecated RetryResult warnings
401
402optional<uint32_t> HOT Scheduler::next_schedule_in(uint32_t now) {
403 // IMPORTANT: This method should only be called from the main thread (loop task).
404 // It performs cleanup and accesses items_[0] without holding a lock, which is only
405 // safe when called from the main thread. Other threads must not call this method.
406
407 // If no items, return empty optional
408 if (!this->cleanup_())
409 return {};
410
411 SchedulerItem *item = this->items_[0];
412 const auto now_64 = this->millis_64_from_(now);
413 const uint64_t next_exec = item->get_next_execution();
414 if (next_exec < now_64)
415 return 0;
416 return next_exec - now_64;
417}
418
419void Scheduler::full_cleanup_removed_items_() {
420 // We hold the lock for the entire cleanup operation because:
421 // 1. We're rebuilding the entire items_ list, so we need exclusive access throughout
422 // 2. Other threads must see either the old state or the new state, not intermediate states
423 // 3. The operation is already expensive (O(n)), so lock overhead is negligible
424 // 4. No operations inside can block or take other locks, so no deadlock risk
425 LockGuard guard{this->lock_};
426
427 // Compact in-place: move valid items forward, recycle removed ones
428 size_t write = 0;
429 for (size_t read = 0; read < this->items_.size(); ++read) {
430 if (!is_item_removed_locked_(this->items_[read])) {
431 if (write != read) {
432 this->items_[write] = this->items_[read];
433 }
434 ++write;
435 } else {
436 this->recycle_item_main_loop_(this->items_[read]);
437 }
438 }
439 this->items_.erase(this->items_.begin() + write, this->items_.end());
440 // Rebuild the heap structure since items are no longer in heap order
441 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
442 this->to_remove_clear_();
443}
444
445#ifndef ESPHOME_THREAD_SINGLE
446void Scheduler::compact_defer_queue_locked_() {
447 // Rare case: new items were added during processing - compact the vector
448 // This only happens when:
449 // 1. A deferred callback calls defer() again, or
450 // 2. Another thread calls defer() while we're processing
451 //
452 // Move unprocessed items (added during this loop) to the front for next iteration
453 //
454 // SAFETY: Compacted items may include cancelled items (marked for removal via
455 // cancel_item_locked_() during execution). This is safe because should_skip_item_()
456 // checks is_item_removed_() before executing, so cancelled items will be skipped
457 // and recycled on the next loop iteration.
458 size_t remaining = this->defer_queue_.size() - this->defer_queue_front_;
459 for (size_t i = 0; i < remaining; i++) {
460 this->defer_queue_[i] = this->defer_queue_[this->defer_queue_front_ + i];
461 }
462 // Use erase() instead of resize() to avoid instantiating _M_default_append
463 // (saves ~156 bytes flash). Erasing from the end is O(1) - no shifting needed.
464 this->defer_queue_.erase(this->defer_queue_.begin() + remaining, this->defer_queue_.end());
465}
466void HOT Scheduler::process_defer_queue_slow_path_(uint32_t &now) {
467 // Process defer queue to guarantee FIFO execution order for deferred items.
468 // Previously, defer() used the heap which gave undefined order for equal timestamps,
469 // causing race conditions on multi-core systems (ESP32, BK7200).
470 // With the defer queue:
471 // - Deferred items (delay=0) go directly to defer_queue_ in set_timer_common_
472 // - Items execute in exact order they were deferred (FIFO guarantee)
473 // - No deferred items exist in to_add_, so processing order doesn't affect correctness
474 // Single-core platforms don't use this queue and fall back to the heap-based approach.
475 //
476 // Note: Items cancelled via cancel_item_locked_() are marked with remove=true but still
477 // processed here. They are skipped during execution by should_skip_item_().
478 // This is intentional - no memory leak occurs.
479 //
480 // We use an index (defer_queue_front_) to track the read position instead of calling
481 // erase() on every pop, which would be O(n). The queue is processed once per loop -
482 // any items added during processing are left for the next loop iteration.
483
484 // Merge lock acquisitions: instead of separate locks for move-out and recycle (2N+1 total),
485 // recycle each item after re-acquiring the lock for the next iteration (N+1 total).
486 // The lock is held across: recycle → loop condition → move-out, then released for execution.
487 SchedulerItem *item;
488
489 this->lock_.lock();
490 // Reset counter and snapshot queue end under lock
491 this->defer_count_clear_();
492 size_t defer_queue_end = this->defer_queue_.size();
493 if (this->defer_queue_front_ >= defer_queue_end) {
494 this->lock_.unlock();
495 return;
496 }
497 while (this->defer_queue_front_ < defer_queue_end) {
498 // Take ownership of the item, leaving nullptr in the vector slot.
499 // This is safe because:
500 // 1. The vector is only cleaned up by cleanup_defer_queue_locked_() at the end of this function
501 // 2. Any code iterating defer_queue_ MUST check for nullptr items (see mark_matching_items_removed_locked_)
502 // 3. The lock protects concurrent access, but the nullptr remains until cleanup
503 item = this->defer_queue_[this->defer_queue_front_];
504 this->defer_queue_[this->defer_queue_front_] = nullptr;
505 this->defer_queue_front_++;
506 this->lock_.unlock();
507
508 // Execute callback without holding lock to prevent deadlocks
509 // if the callback tries to call defer() again
510 if (!this->should_skip_item_(item)) {
511 now = this->execute_item_(item, now);
512 }
513
514 this->lock_.lock();
515 this->recycle_item_main_loop_(item);
516 }
517 // Clean up the queue (lock already held from last recycle or initial acquisition)
518 this->cleanup_defer_queue_locked_();
519 this->lock_.unlock();
520}
521#endif /* not ESPHOME_THREAD_SINGLE */
522
523void HOT Scheduler::call(uint32_t now) {
524#ifndef ESPHOME_THREAD_SINGLE
525 this->process_defer_queue_(now);
526#endif /* not ESPHOME_THREAD_SINGLE */
527
528 // Extend the caller's 32-bit timestamp to 64-bit for scheduler operations
529 const auto now_64 = this->millis_64_from_(now);
530 this->process_to_add();
531
532 // Track if any items were added to to_add_ during callbacks
533 bool has_added_items = false;
534
535#ifdef ESPHOME_DEBUG_SCHEDULER
536 static uint64_t last_print = 0;
537
538 if (now_64 - last_print > 2000) {
539 last_print = now_64;
540 std::vector<SchedulerItem *> old_items;
541 ESP_LOGD(TAG, "Items: count=%zu, pool=%zu, now=%" PRIu64, this->items_.size(), this->scheduler_item_pool_.size(),
542 now_64);
543 // Cleanup before debug output
544 this->cleanup_();
545 while (!this->items_.empty()) {
546 SchedulerItem *item;
547 {
548 LockGuard guard{this->lock_};
549 item = this->pop_raw_locked_();
550 }
551
552 SchedulerNameLog name_log;
553 bool is_cancelled = is_item_removed_(item);
554 ESP_LOGD(TAG, " %s '%s/%s' interval=%" PRIu32 " next_execution in %" PRIu64 "ms at %" PRIu64 "%s",
555 item->get_type_str(), LOG_STR_ARG(item->get_source()),
556 name_log.format(item->get_name_type(), item->get_name(), item->get_name_hash_or_id()), item->interval,
557 item->get_next_execution() - now_64, item->get_next_execution(), is_cancelled ? " [CANCELLED]" : "");
558
559 old_items.push_back(item);
560 }
561 ESP_LOGD(TAG, "\n");
562
563 {
564 LockGuard guard{this->lock_};
565 this->items_ = std::move(old_items);
566 // Rebuild heap after moving items back
567 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
568 }
569 }
570#endif /* ESPHOME_DEBUG_SCHEDULER */
571
572 // Cleanup removed items before processing
573 // First try to clean items from the top of the heap (fast path)
574 this->cleanup_();
575
576 // If we still have too many cancelled items, do a full cleanup
577 // This only happens if cancelled items are stuck in the middle/bottom of the heap
578 if (this->to_remove_count_() >= MAX_LOGICALLY_DELETED_ITEMS) {
579 this->full_cleanup_removed_items_();
580 }
581 // IMPORTANT: This loop uses index-based access (items_[0]), NOT iterators.
582 // This is intentional — fired intervals are pushed back into items_ via
583 // push_back() + push_heap() below, which may reallocate the vector's storage.
584 // Index-based access is safe across reallocations because we re-read items_[0]
585 // at the top of each iteration. Do NOT convert this to a range-based for loop
586 // or iterator-based loop, as that would break when items are added.
587 while (!this->items_.empty()) {
588 // Don't copy-by value yet
589 SchedulerItem *item = this->items_[0];
590 if (item->get_next_execution() > now_64) {
591 // Not reached timeout yet, done for this call
592 break;
593 }
594 // Don't run on failed components
595 if (item->component != nullptr && item->component->is_failed()) {
596 LockGuard guard{this->lock_};
597 this->recycle_item_main_loop_(this->pop_raw_locked_());
598 continue;
599 }
600
601 // Check if item is marked for removal
602 // This handles two cases:
603 // 1. Item was marked for removal after cleanup_() but before we got here
604 // 2. Item is marked for removal but wasn't at the front of the heap during cleanup_()
605#ifdef ESPHOME_THREAD_MULTI_NO_ATOMICS
606 // Multi-threaded platforms without atomics: must take lock to safely read remove flag
607 {
608 LockGuard guard{this->lock_};
609 if (is_item_removed_locked_(item)) {
610 this->recycle_item_main_loop_(this->pop_raw_locked_());
611 this->to_remove_decrement_();
612 continue;
613 }
614 }
615#else
616 // Single-threaded or multi-threaded with atomics: can check without lock
617 if (is_item_removed_(item)) {
618 LockGuard guard{this->lock_};
619 this->recycle_item_main_loop_(this->pop_raw_locked_());
620 this->to_remove_decrement_();
621 continue;
622 }
623#endif
624
625#ifdef ESPHOME_DEBUG_SCHEDULER
626 {
627 SchedulerNameLog name_log;
628 ESP_LOGV(TAG, "Running %s '%s/%s' with interval=%" PRIu32 " next_execution=%" PRIu64 " (now=%" PRIu64 ")",
629 item->get_type_str(), LOG_STR_ARG(item->get_source()),
630 name_log.format(item->get_name_type(), item->get_name(), item->get_name_hash_or_id()), item->interval,
631 item->get_next_execution(), now_64);
632 }
633#endif /* ESPHOME_DEBUG_SCHEDULER */
634
635 // Warning: During callback(), a lot of stuff can happen, including:
636 // - timeouts/intervals get added, potentially invalidating vector pointers
637 // - timeouts/intervals get cancelled
638 now = this->execute_item_(item, now);
639
640 LockGuard guard{this->lock_};
641
642 // Only pop after function call, this ensures we were reachable
643 // during the function call and know if we were cancelled.
644 SchedulerItem *executed_item = this->pop_raw_locked_();
645
646 if (this->is_item_removed_locked_(executed_item)) {
647 // We were removed/cancelled in the function call, recycle and continue
648 this->to_remove_decrement_();
649 this->recycle_item_main_loop_(executed_item);
650 continue;
651 }
652
653 if (executed_item->type == SchedulerItem::INTERVAL) {
654 executed_item->set_next_execution(now_64 + executed_item->interval);
655 // Push directly back into the heap instead of routing through to_add_.
656 // This is safe because:
657 // 1. We're on the main loop and already hold the lock
658 // 2. The item was already popped from items_ via pop_raw_locked_() above
659 // 3. The while loop uses index-based access (items_[0]), not iterators,
660 // so push_back() reallocation cannot invalidate our iteration
661 // 4. push_heap() restores the heap invariant before the next iteration
662 // peeks at items_[0]
663 // This avoids the to_add_ detour and the overhead of
664 // process_to_add_slow_path_() (lock acquisition, vector iteration, clear).
665 this->items_.push_back(executed_item);
666 std::push_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
667 } else {
668 // Timeout completed - recycle it
669 this->recycle_item_main_loop_(executed_item);
670 }
671
672 has_added_items |= !this->to_add_.empty();
673 }
674
675 if (has_added_items) {
676 this->process_to_add();
677 }
678
679#ifdef ESPHOME_DEBUG_SCHEDULER
680 // Verify no items were leaked during this call() cycle.
681 // All items must be in items_, to_add_, defer_queue_, or the pool.
682 // Safe to check here because:
683 // - process_defer_queue_ has already run its cleanup_defer_queue_locked_(),
684 // so defer_queue_ contains no nullptr slots inflating the count.
685 // - The while loop above has finished, so no items are held in local variables;
686 // every item has been returned to a container (items_, to_add_, or pool).
687 // Lock needed to get a consistent snapshot of all containers.
688 {
689 LockGuard guard{this->lock_};
690 this->debug_verify_no_leak_();
691 }
692#endif
693}
694void HOT Scheduler::process_to_add_slow_path_() {
695 LockGuard guard{this->lock_};
696 for (auto *&it : this->to_add_) {
697 if (is_item_removed_locked_(it)) {
698 // Recycle cancelled items
699 this->recycle_item_main_loop_(it);
700 it = nullptr;
701 continue;
702 }
703
704 this->items_.push_back(it);
705 std::push_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
706 }
707 this->to_add_.clear();
708 this->to_add_count_clear_();
709}
710bool HOT Scheduler::cleanup_slow_path_() {
711 // We must hold the lock for the entire cleanup operation because:
712 // 1. We're modifying items_ (via pop_raw_locked_) which requires exclusive access
713 // 2. We're decrementing to_remove_ which is also modified by other threads
714 // (though all modifications are already under lock)
715 // 3. Other threads read items_ when searching for items to cancel in cancel_item_locked_()
716 // 4. We need a consistent view of items_ and to_remove_ throughout the operation
717 // Without the lock, we could access items_ while another thread is reading it,
718 // leading to race conditions
719 LockGuard guard{this->lock_};
720 while (!this->items_.empty()) {
721 SchedulerItem *item = this->items_[0];
722 if (!this->is_item_removed_locked_(item))
723 break;
724 this->to_remove_decrement_();
725 this->recycle_item_main_loop_(this->pop_raw_locked_());
726 }
727 return !this->items_.empty();
728}
729Scheduler::SchedulerItem *HOT Scheduler::pop_raw_locked_() {
730 std::pop_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
731
732 SchedulerItem *item = this->items_.back();
733 this->items_.pop_back();
734 return item;
735}
736
737// Helper to execute a scheduler item
738uint32_t HOT Scheduler::execute_item_(SchedulerItem *item, uint32_t now) {
739 App.set_current_component(item->component);
740 WarnIfComponentBlockingGuard guard{item->component, now};
741 item->callback();
742 return guard.finish();
743}
744
745// Common implementation for cancel operations - handles locking
746bool HOT Scheduler::cancel_item_(Component *component, NameType name_type, const char *static_name, uint32_t hash_or_id,
747 SchedulerItem::Type type, bool match_retry) {
748 LockGuard guard{this->lock_};
749 // Public cancel path uses default find_first=false to cancel ALL matches because
750 // DelayAction parallel mode (skip_cancel=true) can create multiple items with the same key.
751 return this->cancel_item_locked_(component, name_type, static_name, hash_or_id, type, match_retry);
752}
753
754// Helper to cancel matching items - must be called with lock held.
755// When find_first=true, stops after the first match and exits across containers
756// (used by set_timer_common_ where cancel-before-add guarantees at most one match).
757// When find_first=false, cancels ALL matches across all containers (needed for
758// public cancel path where DelayAction parallel mode can create duplicates).
759// name_type determines matching: STATIC_STRING uses static_name, others use hash_or_id
760size_t Scheduler::mark_matching_items_removed_slow_locked_(std::vector<SchedulerItem *> &container,
761 Component *component, NameType name_type,
762 const char *static_name, uint32_t hash_or_id,
763 SchedulerItem::Type type, bool match_retry,
764 bool find_first) {
765 size_t count = 0;
766 for (auto *item : container) {
767 if (this->matches_item_locked_(item, component, name_type, static_name, hash_or_id, type, match_retry)) {
768 this->set_item_removed_(item, true);
769 if (find_first)
770 return 1;
771 count++;
772 }
773 }
774 return count;
775}
776
777bool HOT Scheduler::cancel_item_locked_(Component *component, NameType name_type, const char *static_name,
778 uint32_t hash_or_id, SchedulerItem::Type type, bool match_retry,
779 bool find_first) {
780 // Early return if static string name is invalid
781 if (name_type == NameType::STATIC_STRING && static_name == nullptr) {
782 return false;
783 }
784
785 size_t total_cancelled = 0;
786
787#ifndef ESPHOME_THREAD_SINGLE
788 // Mark items in defer queue as cancelled (they'll be skipped when processed)
789 if (type == SchedulerItem::TIMEOUT) {
790 total_cancelled += this->mark_matching_items_removed_locked_(this->defer_queue_, component, name_type, static_name,
791 hash_or_id, type, match_retry, find_first);
792 if (find_first && total_cancelled > 0)
793 return true;
794 }
795#endif /* not ESPHOME_THREAD_SINGLE */
796
797 // Cancel items in the main heap
798 // We only mark items for removal here - never recycle directly.
799 // The main loop may be executing an item's callback right now, and recycling
800 // would destroy the callback while it's running (use-after-free).
801 // Only the main loop in call() should recycle items after execution completes.
802 {
803 size_t heap_cancelled = this->mark_matching_items_removed_locked_(this->items_, component, name_type, static_name,
804 hash_or_id, type, match_retry, find_first);
805 total_cancelled += heap_cancelled;
806 this->to_remove_add_(heap_cancelled);
807 if (find_first && total_cancelled > 0)
808 return true;
809 }
810
811 // Cancel items in to_add_
812 total_cancelled += this->mark_matching_items_removed_locked_(this->to_add_, component, name_type, static_name,
813 hash_or_id, type, match_retry, find_first);
814
815 return total_cancelled > 0;
816}
817
818bool HOT Scheduler::SchedulerItem::cmp(SchedulerItem *a, SchedulerItem *b) {
819 // High bits are almost always equal (change only on 32-bit rollover ~49 days)
820 // Optimize for common case: check low bits first when high bits are equal
821 return (a->next_execution_high_ == b->next_execution_high_) ? (a->next_execution_low_ > b->next_execution_low_)
822 : (a->next_execution_high_ > b->next_execution_high_);
823}
824
825// Recycle a SchedulerItem back to the pool for reuse.
826// IMPORTANT: Caller must hold the scheduler lock before calling this function.
827// This protects scheduler_item_pool_ from concurrent access by other threads
828// that may be acquiring items from the pool in set_timer_common_().
829void Scheduler::recycle_item_main_loop_(SchedulerItem *item) {
830 if (item == nullptr)
831 return;
832
833 if (this->scheduler_item_pool_.size() < MAX_POOL_SIZE) {
834 // Clear callback to release captured resources
835 item->callback = nullptr;
836 this->scheduler_item_pool_.push_back(item);
837#ifdef ESPHOME_DEBUG_SCHEDULER
838 ESP_LOGD(TAG, "Recycled item to pool (pool size now: %zu)", this->scheduler_item_pool_.size());
839#endif
840 } else {
841#ifdef ESPHOME_DEBUG_SCHEDULER
842 ESP_LOGD(TAG, "Pool full (size: %zu), deleting item", this->scheduler_item_pool_.size());
843#endif
844 delete item;
845#ifdef ESPHOME_DEBUG_SCHEDULER
846 this->debug_live_items_--;
847#endif
848 }
849}
850
851#ifdef ESPHOME_DEBUG_SCHEDULER
852void Scheduler::debug_log_timer_(const SchedulerItem *item, NameType name_type, const char *static_name,
853 uint32_t hash_or_id, SchedulerItem::Type type, uint32_t delay, uint64_t now) {
854 // Validate static strings in debug mode
855 if (name_type == NameType::STATIC_STRING && static_name != nullptr) {
856 validate_static_string(static_name);
857 }
858
859 // Debug logging
860 SchedulerNameLog name_log;
861 const char *type_str = (type == SchedulerItem::TIMEOUT) ? "timeout" : "interval";
862 if (type == SchedulerItem::TIMEOUT) {
863 ESP_LOGD(TAG, "set_%s(name='%s/%s', %s=%" PRIu32 ")", type_str, LOG_STR_ARG(item->get_source()),
864 name_log.format(name_type, static_name, hash_or_id), type_str, delay);
865 } else {
866 ESP_LOGD(TAG, "set_%s(name='%s/%s', %s=%" PRIu32 ", offset=%" PRIu32 ")", type_str, LOG_STR_ARG(item->get_source()),
867 name_log.format(name_type, static_name, hash_or_id), type_str, delay,
868 static_cast<uint32_t>(item->get_next_execution() - now));
869 }
870}
871#endif /* ESPHOME_DEBUG_SCHEDULER */
872
873// Helper to get or create a scheduler item from the pool
874// IMPORTANT: Caller must hold the scheduler lock before calling this function.
875Scheduler::SchedulerItem *Scheduler::get_item_from_pool_locked_() {
876 if (!this->scheduler_item_pool_.empty()) {
877 SchedulerItem *item = this->scheduler_item_pool_.back();
878 this->scheduler_item_pool_.pop_back();
879#ifdef ESPHOME_DEBUG_SCHEDULER
880 ESP_LOGD(TAG, "Reused item from pool (pool size now: %zu)", this->scheduler_item_pool_.size());
881#endif
882 return item;
883 }
884#ifdef ESPHOME_DEBUG_SCHEDULER
885 ESP_LOGD(TAG, "Allocated new item (pool empty)");
886#endif
887 auto *item = new SchedulerItem();
888#ifdef ESPHOME_DEBUG_SCHEDULER
889 this->debug_live_items_++;
890#endif
891 return item;
892}
893
894#ifdef ESPHOME_DEBUG_SCHEDULER
895bool Scheduler::debug_verify_no_leak_() const {
896 // Invariant: every live SchedulerItem must be in exactly one container.
897 // debug_live_items_ tracks allocations minus deletions.
898 size_t accounted = this->items_.size() + this->to_add_.size() + this->scheduler_item_pool_.size();
899#ifndef ESPHOME_THREAD_SINGLE
900 accounted += this->defer_queue_.size();
901#endif
902 if (accounted != this->debug_live_items_) {
903 ESP_LOGE(TAG,
904 "SCHEDULER LEAK DETECTED: live=%" PRIu32 " but accounted=%" PRIu32 " (items=%" PRIu32 " to_add=%" PRIu32
905 " pool=%" PRIu32
906#ifndef ESPHOME_THREAD_SINGLE
907 " defer=%" PRIu32
908#endif
909 ")",
910 static_cast<uint32_t>(this->debug_live_items_), static_cast<uint32_t>(accounted),
911 static_cast<uint32_t>(this->items_.size()), static_cast<uint32_t>(this->to_add_.size()),
912 static_cast<uint32_t>(this->scheduler_item_pool_.size())
913#ifndef ESPHOME_THREAD_SINGLE
914 ,
915 static_cast<uint32_t>(this->defer_queue_.size())
916#endif
917 );
918 assert(false);
919 return false;
920 }
921 return true;
922}
923#endif
924
925} // namespace esphome
void set_current_component(Component *component)
ESPDEPRECATED("set_retry is deprecated and will be removed in 2026.8.0. Use set_timeout or set_interval instead.", "2026.2.0") void set_retry(const std uint32_t uint8_t std::function< RetryResult(uint8_t)> float backoff_increase_factor
Definition component.h:441
const Component * component
Definition component.cpp:34
uint16_t type
static float float b
const char *const TAG
Definition spi.cpp:7
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
const char int const __FlashStringHelper * format
Definition log.h:74
void retry_handler(const std::shared_ptr< RetryArgs > &args)
const char int const __FlashStringHelper va_list args
Definition log.h:74
uint64_t HOT millis_64()
Definition core.cpp:27
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:12
void HOT delay(uint32_t ms)
Definition core.cpp:28
Application App
Global storage of Application pointer - only one Application can exist.
constexpr uint32_t fnv1a_hash(const char *str)
Calculate a FNV-1a hash of str.
Definition helpers.h:822
constexpr uint32_t SCHEDULER_DONT_RUN
Definition component.h:60
static void uint32_t