ESPHome 2025.9.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"
8#include <algorithm>
9#include <cinttypes>
10#include <cstring>
11#include <limits>
12
13namespace esphome {
14
15static const char *const TAG = "scheduler";
16
17static const uint32_t MAX_LOGICALLY_DELETED_ITEMS = 10;
18// Half the 32-bit range - used to detect rollovers vs normal time progression
19static constexpr uint32_t HALF_MAX_UINT32 = std::numeric_limits<uint32_t>::max() / 2;
20// max delay to start an interval sequence
21static constexpr uint32_t MAX_INTERVAL_DELAY = 5000;
22
23// Uncomment to debug scheduler
24// #define ESPHOME_DEBUG_SCHEDULER
25
26#ifdef ESPHOME_DEBUG_SCHEDULER
27// Helper to validate that a pointer looks like it's in static memory
28static void validate_static_string(const char *name) {
29 if (name == nullptr)
30 return;
31
32 // This is a heuristic check - stack and heap pointers are typically
33 // much higher in memory than static data
34 uintptr_t addr = reinterpret_cast<uintptr_t>(name);
35
36 // Create a stack variable to compare against
37 int stack_var;
38 uintptr_t stack_addr = reinterpret_cast<uintptr_t>(&stack_var);
39
40 // If the string pointer is near our stack variable, it's likely on the stack
41 // Using 8KB range as ESP32 main task stack is typically 8192 bytes
42 if (addr > (stack_addr - 0x2000) && addr < (stack_addr + 0x2000)) {
43 ESP_LOGW(TAG,
44 "WARNING: Scheduler name '%s' at %p appears to be on the stack - this is unsafe!\n"
45 " Stack reference at %p",
46 name, name, &stack_var);
47 }
48
49 // Also check if it might be on the heap by seeing if it's in a very different range
50 // This is platform-specific but generally heap is allocated far from static memory
51 static const char *static_str = "test";
52 uintptr_t static_addr = reinterpret_cast<uintptr_t>(static_str);
53
54 // If the address is very far from known static memory, it might be heap
55 if (addr > static_addr + 0x100000 || (static_addr > 0x100000 && addr < static_addr - 0x100000)) {
56 ESP_LOGW(TAG, "WARNING: Scheduler name '%s' at %p might be on heap (static ref at %p)", name, name, static_str);
57 }
58}
59#endif /* ESPHOME_DEBUG_SCHEDULER */
60
61// A note on locking: the `lock_` lock protects the `items_` and `to_add_` containers. It must be taken when writing to
62// them (i.e. when adding/removing items, but not when changing items). As items are only deleted from the loop task,
63// iterating over them from the loop task is fine; but iterating from any other context requires the lock to be held to
64// avoid the main thread modifying the list while it is being accessed.
65
66// Common implementation for both timeout and interval
67void HOT Scheduler::set_timer_common_(Component *component, SchedulerItem::Type type, bool is_static_string,
68 const void *name_ptr, uint32_t delay, std::function<void()> func, bool is_retry) {
69 // Get the name as const char*
70 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
71
72 if (delay == SCHEDULER_DONT_RUN) {
73 // Still need to cancel existing timer if name is not empty
74 LockGuard guard{this->lock_};
75 this->cancel_item_locked_(component, name_cstr, type);
76 return;
77 }
78
79 // Create and populate the scheduler item
80 auto item = make_unique<SchedulerItem>();
81 item->component = component;
82 item->set_name(name_cstr, !is_static_string);
83 item->type = type;
84 item->callback = std::move(func);
85 item->remove = false;
86 item->is_retry = is_retry;
87
88#ifndef ESPHOME_THREAD_SINGLE
89 // Special handling for defer() (delay = 0, type = TIMEOUT)
90 // Single-core platforms don't need thread-safe defer handling
91 if (delay == 0 && type == SchedulerItem::TIMEOUT) {
92 // Put in defer queue for guaranteed FIFO execution
93 LockGuard guard{this->lock_};
94 this->cancel_item_locked_(component, name_cstr, type);
95 this->defer_queue_.push_back(std::move(item));
96 return;
97 }
98#endif /* not ESPHOME_THREAD_SINGLE */
99
100 // Get fresh timestamp for new timer/interval - ensures accurate scheduling
101 const auto now = this->millis_64_(millis()); // Fresh millis() call
102
103 // Type-specific setup
104 if (type == SchedulerItem::INTERVAL) {
105 item->interval = delay;
106 // first execution happens immediately after a random smallish offset
107 // Calculate random offset (0 to min(interval/2, 5s))
108 uint32_t offset = (uint32_t) (std::min(delay / 2, MAX_INTERVAL_DELAY) * random_float());
109 item->next_execution_ = now + offset;
110 ESP_LOGV(TAG, "Scheduler interval for %s is %" PRIu32 "ms, offset %" PRIu32 "ms", name_cstr ? name_cstr : "", delay,
111 offset);
112 } else {
113 item->interval = 0;
114 item->next_execution_ = now + delay;
115 }
116
117#ifdef ESPHOME_DEBUG_SCHEDULER
118 // Validate static strings in debug mode
119 if (is_static_string && name_cstr != nullptr) {
120 validate_static_string(name_cstr);
121 }
122
123 // Debug logging
124 const char *type_str = (type == SchedulerItem::TIMEOUT) ? "timeout" : "interval";
126 ESP_LOGD(TAG, "set_%s(name='%s/%s', %s=%" PRIu32 ")", type_str, item->get_source(),
127 name_cstr ? name_cstr : "(null)", type_str, delay);
128 } else {
129 ESP_LOGD(TAG, "set_%s(name='%s/%s', %s=%" PRIu32 ", offset=%" PRIu32 ")", type_str, item->get_source(),
130 name_cstr ? name_cstr : "(null)", type_str, delay, static_cast<uint32_t>(item->next_execution_ - now));
131 }
132#endif /* ESPHOME_DEBUG_SCHEDULER */
133
134 LockGuard guard{this->lock_};
135
136 // For retries, check if there's a cancelled timeout first
137 if (is_retry && name_cstr != nullptr && type == SchedulerItem::TIMEOUT &&
138 (has_cancelled_timeout_in_container_(this->items_, component, name_cstr, /* match_retry= */ true) ||
139 has_cancelled_timeout_in_container_(this->to_add_, component, name_cstr, /* match_retry= */ true))) {
140 // Skip scheduling - the retry was cancelled
141#ifdef ESPHOME_DEBUG_SCHEDULER
142 ESP_LOGD(TAG, "Skipping retry '%s' - found cancelled item", name_cstr);
143#endif
144 return;
145 }
146
147 // If name is provided, do atomic cancel-and-add
148 // Cancel existing items
149 this->cancel_item_locked_(component, name_cstr, type);
150 // Add new item directly to to_add_
151 // since we have the lock held
152 this->to_add_.push_back(std::move(item));
153}
154
155void HOT Scheduler::set_timeout(Component *component, const char *name, uint32_t timeout, std::function<void()> func) {
156 this->set_timer_common_(component, SchedulerItem::TIMEOUT, true, name, timeout, std::move(func));
157}
158
159void HOT Scheduler::set_timeout(Component *component, const std::string &name, uint32_t timeout,
160 std::function<void()> func) {
161 this->set_timer_common_(component, SchedulerItem::TIMEOUT, false, &name, timeout, std::move(func));
162}
163bool HOT Scheduler::cancel_timeout(Component *component, const std::string &name) {
164 return this->cancel_item_(component, false, &name, SchedulerItem::TIMEOUT);
165}
166bool HOT Scheduler::cancel_timeout(Component *component, const char *name) {
167 return this->cancel_item_(component, true, name, SchedulerItem::TIMEOUT);
168}
169void HOT Scheduler::set_interval(Component *component, const std::string &name, uint32_t interval,
170 std::function<void()> func) {
171 this->set_timer_common_(component, SchedulerItem::INTERVAL, false, &name, interval, std::move(func));
172}
173
174void HOT Scheduler::set_interval(Component *component, const char *name, uint32_t interval,
175 std::function<void()> func) {
176 this->set_timer_common_(component, SchedulerItem::INTERVAL, true, name, interval, std::move(func));
177}
178bool HOT Scheduler::cancel_interval(Component *component, const std::string &name) {
179 return this->cancel_item_(component, false, &name, SchedulerItem::INTERVAL);
180}
181bool HOT Scheduler::cancel_interval(Component *component, const char *name) {
182 return this->cancel_item_(component, true, name, SchedulerItem::INTERVAL);
183}
184
185struct RetryArgs {
186 std::function<RetryResult(uint8_t)> func;
187 uint8_t retry_countdown;
188 uint32_t current_interval;
189 Component *component;
190 std::string name; // Keep as std::string since retry uses it dynamically
191 float backoff_increase_factor;
192 Scheduler *scheduler;
193};
194
195void retry_handler(const std::shared_ptr<RetryArgs> &args) {
196 RetryResult const retry_result = args->func(--args->retry_countdown);
197 if (retry_result == RetryResult::DONE || args->retry_countdown <= 0)
198 return;
199 // second execution of `func` happens after `initial_wait_time`
200 args->scheduler->set_timer_common_(
201 args->component, Scheduler::SchedulerItem::TIMEOUT, false, &args->name, args->current_interval,
202 [args]() { retry_handler(args); }, /* is_retry= */ true);
203 // backoff_increase_factor applied to third & later executions
204 args->current_interval *= args->backoff_increase_factor;
205}
206
207void HOT Scheduler::set_retry_common_(Component *component, bool is_static_string, const void *name_ptr,
208 uint32_t initial_wait_time, uint8_t max_attempts,
209 std::function<RetryResult(uint8_t)> func, float backoff_increase_factor) {
210 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
211
212 if (name_cstr != nullptr)
213 this->cancel_retry(component, name_cstr);
214
215 if (initial_wait_time == SCHEDULER_DONT_RUN)
216 return;
217
218 ESP_LOGVV(TAG, "set_retry(name='%s', initial_wait_time=%" PRIu32 ", max_attempts=%u, backoff_factor=%0.1f)",
219 name_cstr ? name_cstr : "", initial_wait_time, max_attempts, backoff_increase_factor);
220
221 if (backoff_increase_factor < 0.0001) {
222 ESP_LOGE(TAG, "backoff_factor %0.1f too small, using 1.0: %s", backoff_increase_factor, name_cstr ? name_cstr : "");
223 backoff_increase_factor = 1;
224 }
225
226 auto args = std::make_shared<RetryArgs>();
227 args->func = std::move(func);
228 args->retry_countdown = max_attempts;
229 args->current_interval = initial_wait_time;
230 args->component = component;
231 args->name = name_cstr ? name_cstr : ""; // Convert to std::string for RetryArgs
232 args->backoff_increase_factor = backoff_increase_factor;
233 args->scheduler = this;
234
235 // First execution of `func` immediately - use set_timer_common_ with is_retry=true
236 this->set_timer_common_(
237 component, SchedulerItem::TIMEOUT, false, &args->name, 0, [args]() { retry_handler(args); },
238 /* is_retry= */ true);
239}
240
241void HOT Scheduler::set_retry(Component *component, const std::string &name, uint32_t initial_wait_time,
242 uint8_t max_attempts, std::function<RetryResult(uint8_t)> func,
243 float backoff_increase_factor) {
244 this->set_retry_common_(component, false, &name, initial_wait_time, max_attempts, std::move(func),
245 backoff_increase_factor);
246}
247
248void HOT Scheduler::set_retry(Component *component, const char *name, uint32_t initial_wait_time, uint8_t max_attempts,
249 std::function<RetryResult(uint8_t)> func, float backoff_increase_factor) {
250 this->set_retry_common_(component, true, name, initial_wait_time, max_attempts, std::move(func),
251 backoff_increase_factor);
252}
253bool HOT Scheduler::cancel_retry(Component *component, const std::string &name) {
254 return this->cancel_retry(component, name.c_str());
255}
256
257bool HOT Scheduler::cancel_retry(Component *component, const char *name) {
258 // Cancel timeouts that have is_retry flag set
259 LockGuard guard{this->lock_};
260 return this->cancel_item_locked_(component, name, SchedulerItem::TIMEOUT, /* match_retry= */ true);
261}
262
264 // IMPORTANT: This method should only be called from the main thread (loop task).
265 // It performs cleanup and accesses items_[0] without holding a lock, which is only
266 // safe when called from the main thread. Other threads must not call this method.
267
268 // If no items, return empty optional
269 if (this->cleanup_() == 0)
270 return {};
271
272 auto &item = this->items_[0];
273 // Convert the fresh timestamp from caller (usually Application::loop()) to 64-bit
274 const auto now_64 = this->millis_64_(now); // 'now' from parameter - fresh from caller
275 if (item->next_execution_ < now_64)
276 return 0;
277 return item->next_execution_ - now_64;
278}
279void HOT Scheduler::call(uint32_t now) {
280#ifndef ESPHOME_THREAD_SINGLE
281 // Process defer queue first to guarantee FIFO execution order for deferred items.
282 // Previously, defer() used the heap which gave undefined order for equal timestamps,
283 // causing race conditions on multi-core systems (ESP32, BK7200).
284 // With the defer queue:
285 // - Deferred items (delay=0) go directly to defer_queue_ in set_timer_common_
286 // - Items execute in exact order they were deferred (FIFO guarantee)
287 // - No deferred items exist in to_add_, so processing order doesn't affect correctness
288 // Single-core platforms don't use this queue and fall back to the heap-based approach.
289 //
290 // Note: Items cancelled via cancel_item_locked_() are marked with remove=true but still
291 // processed here. They are removed from the queue normally via pop_front() but skipped
292 // during execution by should_skip_item_(). This is intentional - no memory leak occurs.
293 while (!this->defer_queue_.empty()) {
294 // The outer check is done without a lock for performance. If the queue
295 // appears non-empty, we lock and process an item. We don't need to check
296 // empty() again inside the lock because only this thread can remove items.
297 std::unique_ptr<SchedulerItem> item;
298 {
299 LockGuard lock(this->lock_);
300 item = std::move(this->defer_queue_.front());
301 this->defer_queue_.pop_front();
302 }
303
304 // Execute callback without holding lock to prevent deadlocks
305 // if the callback tries to call defer() again
306 if (!this->should_skip_item_(item.get())) {
307 this->execute_item_(item.get(), now);
308 }
309 }
310#endif /* not ESPHOME_THREAD_SINGLE */
311
312 // Convert the fresh timestamp from main loop to 64-bit for scheduler operations
313 const auto now_64 = this->millis_64_(now); // 'now' from parameter - fresh from Application::loop()
314 this->process_to_add();
315
316#ifdef ESPHOME_DEBUG_SCHEDULER
317 static uint64_t last_print = 0;
318
319 if (now_64 - last_print > 2000) {
320 last_print = now_64;
321 std::vector<std::unique_ptr<SchedulerItem>> old_items;
322#ifdef ESPHOME_THREAD_MULTI_ATOMICS
323 const auto last_dbg = this->last_millis_.load(std::memory_order_relaxed);
324 const auto major_dbg = this->millis_major_.load(std::memory_order_relaxed);
325 ESP_LOGD(TAG, "Items: count=%zu, now=%" PRIu64 " (%" PRIu16 ", %" PRIu32 ")", this->items_.size(), now_64,
326 major_dbg, last_dbg);
327#else /* not ESPHOME_THREAD_MULTI_ATOMICS */
328 ESP_LOGD(TAG, "Items: count=%zu, now=%" PRIu64 " (%" PRIu16 ", %" PRIu32 ")", this->items_.size(), now_64,
329 this->millis_major_, this->last_millis_);
330#endif /* else ESPHOME_THREAD_MULTI_ATOMICS */
331 // Cleanup before debug output
332 this->cleanup_();
333 while (!this->items_.empty()) {
334 std::unique_ptr<SchedulerItem> item;
335 {
336 LockGuard guard{this->lock_};
337 item = std::move(this->items_[0]);
338 this->pop_raw_();
339 }
340
341 const char *name = item->get_name();
342 ESP_LOGD(TAG, " %s '%s/%s' interval=%" PRIu32 " next_execution in %" PRIu64 "ms at %" PRIu64,
343 item->get_type_str(), item->get_source(), name ? name : "(null)", item->interval,
344 item->next_execution_ - now_64, item->next_execution_);
345
346 old_items.push_back(std::move(item));
347 }
348 ESP_LOGD(TAG, "\n");
349
350 {
351 LockGuard guard{this->lock_};
352 this->items_ = std::move(old_items);
353 // Rebuild heap after moving items back
354 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
355 }
356 }
357#endif /* ESPHOME_DEBUG_SCHEDULER */
358
359 // If we have too many items to remove
360 if (this->to_remove_ > MAX_LOGICALLY_DELETED_ITEMS) {
361 // We hold the lock for the entire cleanup operation because:
362 // 1. We're rebuilding the entire items_ list, so we need exclusive access throughout
363 // 2. Other threads must see either the old state or the new state, not intermediate states
364 // 3. The operation is already expensive (O(n)), so lock overhead is negligible
365 // 4. No operations inside can block or take other locks, so no deadlock risk
366 LockGuard guard{this->lock_};
367
368 std::vector<std::unique_ptr<SchedulerItem>> valid_items;
369
370 // Move all non-removed items to valid_items
371 for (auto &item : this->items_) {
372 if (!item->remove) {
373 valid_items.push_back(std::move(item));
374 }
375 }
376
377 // Replace items_ with the filtered list
378 this->items_ = std::move(valid_items);
379 // Rebuild the heap structure since items are no longer in heap order
380 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
381 this->to_remove_ = 0;
382 }
383
384 // Cleanup removed items before processing
385 this->cleanup_();
386 while (!this->items_.empty()) {
387 // use scoping to indicate visibility of `item` variable
388 {
389 // Don't copy-by value yet
390 auto &item = this->items_[0];
391 if (item->next_execution_ > now_64) {
392 // Not reached timeout yet, done for this call
393 break;
394 }
395 // Don't run on failed components
396 if (item->component != nullptr && item->component->is_failed()) {
397 LockGuard guard{this->lock_};
398 this->pop_raw_();
399 continue;
400 }
401#ifdef ESPHOME_DEBUG_SCHEDULER
402 const char *item_name = item->get_name();
403 ESP_LOGV(TAG, "Running %s '%s/%s' with interval=%" PRIu32 " next_execution=%" PRIu64 " (now=%" PRIu64 ")",
404 item->get_type_str(), item->get_source(), item_name ? item_name : "(null)", item->interval,
405 item->next_execution_, now_64);
406#endif /* ESPHOME_DEBUG_SCHEDULER */
407
408 // Warning: During callback(), a lot of stuff can happen, including:
409 // - timeouts/intervals get added, potentially invalidating vector pointers
410 // - timeouts/intervals get cancelled
411 this->execute_item_(item.get(), now);
412 }
413
414 {
415 LockGuard guard{this->lock_};
416
417 // new scope, item from before might have been moved in the vector
418 auto item = std::move(this->items_[0]);
419 // Only pop after function call, this ensures we were reachable
420 // during the function call and know if we were cancelled.
421 this->pop_raw_();
422
423 if (item->remove) {
424 // We were removed/cancelled in the function call, stop
425 this->to_remove_--;
426 continue;
427 }
428
429 if (item->type == SchedulerItem::INTERVAL) {
430 item->next_execution_ = now_64 + item->interval;
431 // Add new item directly to to_add_
432 // since we have the lock held
433 this->to_add_.push_back(std::move(item));
434 }
435 }
436 }
437
438 this->process_to_add();
439}
441 LockGuard guard{this->lock_};
442 for (auto &it : this->to_add_) {
443 if (it->remove) {
444 continue;
445 }
446
447 this->items_.push_back(std::move(it));
448 std::push_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
449 }
450 this->to_add_.clear();
451}
453 // Fast path: if nothing to remove, just return the current size
454 // Reading to_remove_ without lock is safe because:
455 // 1. We only call this from the main thread during call()
456 // 2. If it's 0, there's definitely nothing to cleanup
457 // 3. If it becomes non-zero after we check, cleanup will happen on the next loop iteration
458 // 4. Not all platforms support atomics, so we accept this race in favor of performance
459 // 5. The worst case is a one-loop-iteration delay in cleanup, which is harmless
460 if (this->to_remove_ == 0)
461 return this->items_.size();
462
463 // We must hold the lock for the entire cleanup operation because:
464 // 1. We're modifying items_ (via pop_raw_) which requires exclusive access
465 // 2. We're decrementing to_remove_ which is also modified by other threads
466 // (though all modifications are already under lock)
467 // 3. Other threads read items_ when searching for items to cancel in cancel_item_locked_()
468 // 4. We need a consistent view of items_ and to_remove_ throughout the operation
469 // Without the lock, we could access items_ while another thread is reading it,
470 // leading to race conditions
471 LockGuard guard{this->lock_};
472 while (!this->items_.empty()) {
473 auto &item = this->items_[0];
474 if (!item->remove)
475 break;
476 this->to_remove_--;
477 this->pop_raw_();
478 }
479 return this->items_.size();
480}
482 std::pop_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
483 this->items_.pop_back();
484}
485
486// Helper to execute a scheduler item
487void HOT Scheduler::execute_item_(SchedulerItem *item, uint32_t now) {
488 App.set_current_component(item->component);
489 WarnIfComponentBlockingGuard guard{item->component, now};
490 item->callback();
491 guard.finish();
492}
493
494// Common implementation for cancel operations
495bool HOT Scheduler::cancel_item_(Component *component, bool is_static_string, const void *name_ptr,
496 SchedulerItem::Type type) {
497 // Get the name as const char*
498 const char *name_cstr = this->get_name_cstr_(is_static_string, name_ptr);
499
500 // obtain lock because this function iterates and can be called from non-loop task context
501 LockGuard guard{this->lock_};
502 return this->cancel_item_locked_(component, name_cstr, type);
503}
504
505// Helper to cancel items by name - must be called with lock held
506bool HOT Scheduler::cancel_item_locked_(Component *component, const char *name_cstr, SchedulerItem::Type type,
507 bool match_retry) {
508 // Early return if name is invalid - no items to cancel
509 if (name_cstr == nullptr) {
510 return false;
511 }
512
513 size_t total_cancelled = 0;
514
515 // Check all containers for matching items
516#ifndef ESPHOME_THREAD_SINGLE
517 // Only check defer queue for timeouts (intervals never go there)
519 for (auto &item : this->defer_queue_) {
520 if (this->matches_item_(item, component, name_cstr, type, match_retry)) {
521 item->remove = true;
522 total_cancelled++;
523 }
524 }
525 }
526#endif /* not ESPHOME_THREAD_SINGLE */
527
528 // Cancel items in the main heap
529 for (auto &item : this->items_) {
530 if (this->matches_item_(item, component, name_cstr, type, match_retry)) {
531 item->remove = true;
532 total_cancelled++;
533 this->to_remove_++; // Track removals for heap items
534 }
535 }
536
537 // Cancel items in to_add_
538 for (auto &item : this->to_add_) {
539 if (this->matches_item_(item, component, name_cstr, type, match_retry)) {
540 item->remove = true;
541 total_cancelled++;
542 // Don't track removals for to_add_ items
543 }
544 }
545
546 return total_cancelled > 0;
547}
548
549uint64_t Scheduler::millis_64_(uint32_t now) {
550 // THREAD SAFETY NOTE:
551 // This function has three implementations, based on the precompiler flags
552 // - ESPHOME_THREAD_SINGLE - Runs on single-threaded platforms (ESP8266, RP2040, etc.)
553 // - ESPHOME_THREAD_MULTI_NO_ATOMICS - Runs on multi-threaded platforms without atomics (LibreTiny)
554 // - ESPHOME_THREAD_MULTI_ATOMICS - Runs on multi-threaded platforms with atomics (ESP32, HOST, etc.)
555 //
556 // Make sure all changes are synchronized if you edit this function.
557 //
558 // IMPORTANT: Always pass fresh millis() values to this function. The implementation
559 // handles out-of-order timestamps between threads, but minimizing time differences
560 // helps maintain accuracy.
561 //
562
563#ifdef ESPHOME_THREAD_SINGLE
564 // This is the single core implementation.
565 //
566 // Single-core platforms have no concurrency, so this is a simple implementation
567 // that just tracks 32-bit rollover (every 49.7 days) without any locking or atomics.
568
569 uint16_t major = this->millis_major_;
570 uint32_t last = this->last_millis_;
571
572 // Check for rollover
573 if (now < last && (last - now) > HALF_MAX_UINT32) {
574 this->millis_major_++;
575 major++;
576#ifdef ESPHOME_DEBUG_SCHEDULER
577 ESP_LOGD(TAG, "Detected true 32-bit rollover at %" PRIu32 "ms (was %" PRIu32 ")", now, last);
578#endif /* ESPHOME_DEBUG_SCHEDULER */
579 }
580
581 // Only update if time moved forward
582 if (now > last) {
583 this->last_millis_ = now;
584 }
585
586 // Combine major (high 32 bits) and now (low 32 bits) into 64-bit time
587 return now + (static_cast<uint64_t>(major) << 32);
588
589#elif defined(ESPHOME_THREAD_MULTI_NO_ATOMICS)
590 // This is the multi core no atomics implementation.
591 //
592 // Without atomics, this implementation uses locks more aggressively:
593 // 1. Always locks when near the rollover boundary (within 10 seconds)
594 // 2. Always locks when detecting a large backwards jump
595 // 3. Updates without lock in normal forward progression (accepting minor races)
596 // This is less efficient but necessary without atomic operations.
597 uint16_t major = this->millis_major_;
598 uint32_t last = this->last_millis_;
599
600 // Define a safe window around the rollover point (10 seconds)
601 // This covers any reasonable scheduler delays or thread preemption
602 static const uint32_t ROLLOVER_WINDOW = 10000; // 10 seconds in milliseconds
603
604 // Check if we're near the rollover boundary (close to std::numeric_limits<uint32_t>::max() or just past 0)
605 bool near_rollover = (last > (std::numeric_limits<uint32_t>::max() - ROLLOVER_WINDOW)) || (now < ROLLOVER_WINDOW);
606
607 if (near_rollover || (now < last && (last - now) > HALF_MAX_UINT32)) {
608 // Near rollover or detected a rollover - need lock for safety
609 LockGuard guard{this->lock_};
610 // Re-read with lock held
611 last = this->last_millis_;
612
613 if (now < last && (last - now) > HALF_MAX_UINT32) {
614 // True rollover detected (happens every ~49.7 days)
615 this->millis_major_++;
616 major++;
617#ifdef ESPHOME_DEBUG_SCHEDULER
618 ESP_LOGD(TAG, "Detected true 32-bit rollover at %" PRIu32 "ms (was %" PRIu32 ")", now, last);
619#endif /* ESPHOME_DEBUG_SCHEDULER */
620 }
621 // Update last_millis_ while holding lock
622 this->last_millis_ = now;
623 } else if (now > last) {
624 // Normal case: Not near rollover and time moved forward
625 // Update without lock. While this may cause minor races (microseconds of
626 // backwards time movement), they're acceptable because:
627 // 1. The scheduler operates at millisecond resolution, not microsecond
628 // 2. We've already prevented the critical rollover race condition
629 // 3. Any backwards movement is orders of magnitude smaller than scheduler delays
630 this->last_millis_ = now;
631 }
632 // If now <= last and we're not near rollover, don't update
633 // This minimizes backwards time movement
634
635 // Combine major (high 32 bits) and now (low 32 bits) into 64-bit time
636 return now + (static_cast<uint64_t>(major) << 32);
637
638#elif defined(ESPHOME_THREAD_MULTI_ATOMICS)
639 // This is the multi core with atomics implementation.
640 //
641 // Uses atomic operations with acquire/release semantics to ensure coherent
642 // reads of millis_major_ and last_millis_ across cores. Features:
643 // 1. Epoch-coherency retry loop to handle concurrent updates
644 // 2. Lock only taken for actual rollover detection and update
645 // 3. Lock-free CAS updates for normal forward time progression
646 // 4. Memory ordering ensures cores see consistent time values
647
648 for (;;) {
649 uint16_t major = this->millis_major_.load(std::memory_order_acquire);
650
651 /*
652 * Acquire so that if we later decide **not** to take the lock we still
653 * observe a `millis_major_` value coherent with the loaded `last_millis_`.
654 * The acquire load ensures any later read of `millis_major_` sees its
655 * corresponding increment.
656 */
657 uint32_t last = this->last_millis_.load(std::memory_order_acquire);
658
659 // If we might be near a rollover (large backwards jump), take the lock for the entire operation
660 // This ensures rollover detection and last_millis_ update are atomic together
661 if (now < last && (last - now) > HALF_MAX_UINT32) {
662 // Potential rollover - need lock for atomic rollover detection + update
663 LockGuard guard{this->lock_};
664 // Re-read with lock held; mutex already provides ordering
665 last = this->last_millis_.load(std::memory_order_relaxed);
666
667 if (now < last && (last - now) > HALF_MAX_UINT32) {
668 // True rollover detected (happens every ~49.7 days)
669 this->millis_major_.fetch_add(1, std::memory_order_relaxed);
670 major++;
671#ifdef ESPHOME_DEBUG_SCHEDULER
672 ESP_LOGD(TAG, "Detected true 32-bit rollover at %" PRIu32 "ms (was %" PRIu32 ")", now, last);
673#endif /* ESPHOME_DEBUG_SCHEDULER */
674 }
675 /*
676 * Update last_millis_ while holding the lock to prevent races
677 * Publish the new low-word *after* bumping `millis_major_` (done above)
678 * so readers never see a mismatched pair.
679 */
680 this->last_millis_.store(now, std::memory_order_release);
681 } else {
682 // Normal case: Try lock-free update, but only allow forward movement within same epoch
683 // This prevents accidentally moving backwards across a rollover boundary
684 while (now > last && (now - last) < HALF_MAX_UINT32) {
685 if (this->last_millis_.compare_exchange_weak(last, now,
686 std::memory_order_release, // success
687 std::memory_order_relaxed)) { // failure
688 break;
689 }
690 // CAS failure means no data was published; relaxed is fine
691 // last is automatically updated by compare_exchange_weak if it fails
692 }
693 }
694 uint16_t major_end = this->millis_major_.load(std::memory_order_relaxed);
695 if (major_end == major)
696 return now + (static_cast<uint64_t>(major) << 32);
697 }
698 // Unreachable - the loop always returns when major_end == major
699 __builtin_unreachable();
700
701#else
702#error \
703 "No platform threading model defined. One of ESPHOME_THREAD_SINGLE, ESPHOME_THREAD_MULTI_NO_ATOMICS, or ESPHOME_THREAD_MULTI_ATOMICS must be defined."
704#endif
705}
706
707bool HOT Scheduler::SchedulerItem::cmp(const std::unique_ptr<SchedulerItem> &a,
708 const std::unique_ptr<SchedulerItem> &b) {
709 return a->next_execution_ > b->next_execution_;
710}
711
712} // namespace esphome
void set_current_component(Component *component)
Helper class that wraps a mutex with a RAII-style API.
Definition helpers.h:703
void set_retry_common_(Component *component, bool is_static_string, const void *name_ptr, uint32_t initial_wait_time, uint8_t max_attempts, std::function< RetryResult(uint8_t)> func, float backoff_increase_factor)
bool cancel_retry(Component *component, const std::string &name)
void set_timer_common_(Component *component, SchedulerItem::Type type, bool is_static_string, const void *name_ptr, uint32_t delay, std::function< void()> func, bool is_retry=false)
Definition scheduler.cpp:67
void set_retry(Component *component, const std::string &name, uint32_t initial_wait_time, uint8_t max_attempts, std::function< RetryResult(uint8_t)> func, float backoff_increase_factor=1.0f)
void call(uint32_t now)
bool cancel_timeout(Component *component, const std::string &name)
bool cancel_interval(Component *component, const std::string &name)
void set_timeout(Component *component, const std::string &name, uint32_t timeout, std::function< void()> func)
void set_interval(Component *component, const std::string &name, uint32_t interval, std::function< void()> func)
uint64_t millis_64_(uint32_t now)
optional< uint32_t > next_schedule_in(uint32_t now)
uint8_t type
const char *const TAG
Definition spi.cpp:8
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
float random_float()
Return a random float between 0 and 1.
Definition helpers.cpp:143
void retry_handler(const std::shared_ptr< RetryArgs > &args)
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:28
Application App
Global storage of Application pointer - only one Application can exist.
static bool cmp(const std::unique_ptr< SchedulerItem > &a, const std::unique_ptr< SchedulerItem > &b)