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