15static const char *
const TAG =
"scheduler";
24static constexpr size_t MAX_POOL_SIZE = 5;
29static constexpr uint32_t MAX_LOGICALLY_DELETED_ITEMS = 5;
31static constexpr uint32_t MAX_INTERVAL_DELAY = 5000;
33#if defined(ESPHOME_LOG_HAS_VERBOSE) || defined(ESPHOME_DEBUG_SCHEDULER)
37struct SchedulerNameLog {
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) {
48 ESPHOME_strncpy_P(buffer, ESPHOME_PSTR(
"(null)"),
sizeof(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);
53 }
else if (name_type == NameType::NUMERIC_ID) {
54 ESPHOME_snprintf_P(buffer,
sizeof(buffer), ESPHOME_PSTR(
"id:%" PRIu32), hash_or_id);
57 ESPHOME_snprintf_P(buffer,
sizeof(buffer), ESPHOME_PSTR(
"iid:%" PRIu32), hash_or_id);
67#ifdef ESPHOME_DEBUG_SCHEDULER
69static void validate_static_string(
const char *name) {
75 uintptr_t addr =
reinterpret_cast<uintptr_t
>(name);
79 uintptr_t stack_addr =
reinterpret_cast<uintptr_t
>(&stack_var);
83 if (addr > (stack_addr - 0x2000) && addr < (stack_addr + 0x2000)) {
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);
92 static const char *static_str =
"test";
93 uintptr_t static_addr =
reinterpret_cast<uintptr_t
>(static_str);
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);
117bool Scheduler::is_retry_cancelled_locked_(Component *
component, NameType name_type,
const char *static_name,
119 for (
auto *container : {&this->items_, &this->to_add_}) {
120 for (
auto *item : *container) {
121 if (item !=
nullptr && this->is_item_removed_locked_(item) &&
122 this->matches_item_locked_(item,
component, name_type, static_name, hash_or_id, SchedulerItem::TIMEOUT,
133void HOT Scheduler::set_timer_common_(Component *
component, SchedulerItem::Type
type, NameType name_type,
135 std::function<
void()> &&func,
bool is_retry,
bool skip_cancel) {
139 LockGuard guard{this->lock_};
140 this->cancel_item_locked_(
component, name_type, static_name, hash_or_id,
type);
146 LockGuard guard{this->lock_};
151 if (is_retry &&
delay != 0 && (name_type != NameType::STATIC_STRING || static_name !=
nullptr) &&
152 type == SchedulerItem::TIMEOUT &&
153 this->is_retry_cancelled_locked_(
component, name_type, static_name, hash_or_id)) {
154#ifdef ESPHOME_DEBUG_SCHEDULER
155 SchedulerNameLog skip_name_log;
156 ESP_LOGD(TAG,
"Skipping retry '%s' - found cancelled item",
157 skip_name_log.format(name_type, static_name, hash_or_id));
163 SchedulerItem *item = this->get_item_from_pool_locked_();
165 item->set_name(name_type, static_name, hash_or_id);
167 item->callback = std::move(func);
169 this->set_item_removed_(item,
false);
170 item->is_retry = is_retry;
174 auto *target = &this->to_add_;
176#ifndef ESPHOME_THREAD_SINGLE
179 if (
delay == 0 &&
type == SchedulerItem::TIMEOUT) {
181 target = &this->defer_queue_;
189 if (
type == SchedulerItem::INTERVAL) {
190 item->interval =
delay;
193 item->set_next_execution(now_64 + offset);
194#ifdef ESPHOME_LOG_HAS_VERBOSE
195 SchedulerNameLog name_log;
196 ESP_LOGV(TAG,
"Scheduler interval for %s is %" PRIu32
"ms, offset %" PRIu32
"ms",
197 name_log.format(name_type, static_name, hash_or_id),
delay, offset);
201 item->set_next_execution(now_64 +
delay);
204#ifdef ESPHOME_DEBUG_SCHEDULER
205 this->debug_log_timer_(item, name_type, static_name, hash_or_id,
type,
delay, now_64);
211 this->cancel_item_locked_(
component, name_type, static_name, hash_or_id,
type);
213 target->push_back(item);
214 if (target == &this->to_add_) {
215 this->to_add_count_increment_();
217#ifndef ESPHOME_THREAD_SINGLE
219 this->defer_count_increment_();
224void HOT Scheduler::set_timeout(Component *
component,
const char *name,
uint32_t timeout,
225 std::function<
void()> &&func) {
226 this->set_timer_common_(
component, SchedulerItem::TIMEOUT, NameType::STATIC_STRING, name, 0, timeout,
230void HOT Scheduler::set_timeout(Component *
component,
const std::string &name,
uint32_t timeout,
231 std::function<
void()> &&func) {
232 this->set_timer_common_(
component, SchedulerItem::TIMEOUT, NameType::HASHED_STRING,
nullptr,
fnv1a_hash(name),
233 timeout, std::move(func));
236 this->set_timer_common_(
component, SchedulerItem::TIMEOUT, NameType::NUMERIC_ID,
nullptr,
id, timeout,
239bool HOT Scheduler::cancel_timeout(Component *
component,
const std::string &name) {
240 return this->cancel_item_(
component, NameType::HASHED_STRING,
nullptr,
fnv1a_hash(name), SchedulerItem::TIMEOUT);
242bool HOT Scheduler::cancel_timeout(Component *
component,
const char *name) {
243 return this->cancel_item_(
component, NameType::STATIC_STRING, name, 0, SchedulerItem::TIMEOUT);
246 return this->cancel_item_(
component, NameType::NUMERIC_ID,
nullptr,
id, SchedulerItem::TIMEOUT);
248void HOT Scheduler::set_interval(Component *
component,
const std::string &name,
uint32_t interval,
249 std::function<
void()> &&func) {
250 this->set_timer_common_(
component, SchedulerItem::INTERVAL, NameType::HASHED_STRING,
nullptr,
fnv1a_hash(name),
251 interval, std::move(func));
254void HOT Scheduler::set_interval(Component *
component,
const char *name,
uint32_t interval,
255 std::function<
void()> &&func) {
256 this->set_timer_common_(
component, SchedulerItem::INTERVAL, NameType::STATIC_STRING, name, 0, interval,
260 this->set_timer_common_(
component, SchedulerItem::INTERVAL, NameType::NUMERIC_ID,
nullptr,
id, interval,
263bool HOT Scheduler::cancel_interval(Component *
component,
const std::string &name) {
264 return this->cancel_item_(
component, NameType::HASHED_STRING,
nullptr,
fnv1a_hash(name), SchedulerItem::INTERVAL);
266bool HOT Scheduler::cancel_interval(Component *
component,
const char *name) {
267 return this->cancel_item_(
component, NameType::STATIC_STRING, name, 0, SchedulerItem::INTERVAL);
270 return this->cancel_item_(
component, NameType::NUMERIC_ID,
nullptr,
id, SchedulerItem::INTERVAL);
275#pragma GCC diagnostic push
276#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
282 Scheduler *scheduler;
285 const char *static_name;
289 float backoff_increase_factor;
290 Scheduler::NameType name_type;
291 uint8_t retry_countdown;
301 const char *static_name = (
args->name_type == Scheduler::NameType::STATIC_STRING) ?
args->name_.static_name :
nullptr;
302 uint32_t hash_or_id = (
args->name_type != Scheduler::NameType::STATIC_STRING) ?
args->name_.hash_or_id : 0;
303 args->scheduler->set_timer_common_(
304 args->component, Scheduler::SchedulerItem::TIMEOUT,
args->name_type, static_name, hash_or_id,
305 args->current_interval, [
args]() { retry_handler(args); },
308 args->current_interval *=
args->backoff_increase_factor;
311void HOT Scheduler::set_retry_common_(Component *
component, NameType name_type,
const char *static_name,
313 std::function<
RetryResult(uint8_t)> func,
float backoff_increase_factor) {
314 this->cancel_retry_(
component, name_type, static_name, hash_or_id);
319#ifdef ESPHOME_LOG_HAS_VERY_VERBOSE
321 SchedulerNameLog name_log;
322 ESP_LOGVV(TAG,
"set_retry(name='%s', initial_wait_time=%" PRIu32
", max_attempts=%u, backoff_factor=%0.1f)",
323 name_log.format(name_type, static_name, hash_or_id), initial_wait_time, max_attempts,
324 backoff_increase_factor);
328 if (backoff_increase_factor < 0.0001) {
329 ESP_LOGE(TAG,
"set_retry: backoff_factor %0.1f too small, using 1.0: %s", backoff_increase_factor,
330 (name_type == NameType::STATIC_STRING && static_name) ? static_name :
"");
331 backoff_increase_factor = 1;
334 auto args = std::make_shared<RetryArgs>();
335 args->func = std::move(func);
337 args->scheduler =
this;
338 args->name_type = name_type;
339 if (name_type == NameType::STATIC_STRING) {
340 args->name_.static_name = static_name;
342 args->name_.hash_or_id = hash_or_id;
344 args->current_interval = initial_wait_time;
346 args->retry_countdown = max_attempts;
349 this->set_timer_common_(
354void HOT Scheduler::set_retry(Component *
component,
const char *name,
uint32_t initial_wait_time, uint8_t max_attempts,
355 std::function<
RetryResult(uint8_t)> func,
float backoff_increase_factor) {
356 this->set_retry_common_(
component, NameType::STATIC_STRING, name, 0, initial_wait_time, max_attempts, std::move(func),
357 backoff_increase_factor);
360bool HOT Scheduler::cancel_retry_(Component *
component, NameType name_type,
const char *static_name,
362 return this->cancel_item_(
component, name_type, static_name, hash_or_id, SchedulerItem::TIMEOUT,
365bool HOT Scheduler::cancel_retry(Component *
component,
const char *name) {
366 return this->cancel_retry_(
component, NameType::STATIC_STRING, name, 0);
369void HOT Scheduler::set_retry(Component *
component,
const std::string &name,
uint32_t initial_wait_time,
370 uint8_t max_attempts, std::function<
RetryResult(uint8_t)> func,
371 float backoff_increase_factor) {
372 this->set_retry_common_(
component, NameType::HASHED_STRING,
nullptr,
fnv1a_hash(name), initial_wait_time,
373 max_attempts, std::move(func), backoff_increase_factor);
376bool HOT Scheduler::cancel_retry(Component *
component,
const std::string &name) {
381 std::function<
RetryResult(uint8_t)> func,
float backoff_increase_factor) {
382 this->set_retry_common_(
component, NameType::NUMERIC_ID,
nullptr,
id, initial_wait_time, max_attempts,
383 std::move(func), backoff_increase_factor);
387 return this->cancel_retry_(
component, NameType::NUMERIC_ID,
nullptr,
id);
390#pragma GCC diagnostic pop
392optional<uint32_t> HOT Scheduler::next_schedule_in(
uint32_t now) {
398 if (!this->cleanup_())
401 SchedulerItem *item = this->items_[0];
402 const auto now_64 = this->millis_64_from_(now);
403 const uint64_t next_exec = item->get_next_execution();
404 if (next_exec < now_64)
406 return next_exec - now_64;
409void Scheduler::full_cleanup_removed_items_() {
415 LockGuard guard{this->lock_};
419 for (
size_t read = 0; read < this->items_.size(); ++read) {
420 if (!is_item_removed_locked_(this->items_[read])) {
422 this->items_[write] = this->items_[read];
426 this->recycle_item_main_loop_(this->items_[read]);
429 this->items_.erase(this->items_.begin() + write, this->items_.end());
431 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
432 this->to_remove_clear_();
435#ifndef ESPHOME_THREAD_SINGLE
436void Scheduler::compact_defer_queue_locked_() {
448 size_t remaining = this->defer_queue_.size() - this->defer_queue_front_;
449 for (
size_t i = 0; i < remaining; i++) {
450 this->defer_queue_[i] = this->defer_queue_[this->defer_queue_front_ + i];
454 this->defer_queue_.erase(this->defer_queue_.begin() + remaining, this->defer_queue_.end());
458void HOT Scheduler::call(
uint32_t now) {
459#ifndef ESPHOME_THREAD_SINGLE
460 this->process_defer_queue_(now);
464 const auto now_64 = this->millis_64_from_(now);
465 this->process_to_add();
468 bool has_added_items =
false;
470#ifdef ESPHOME_DEBUG_SCHEDULER
471 static uint64_t last_print = 0;
473 if (now_64 - last_print > 2000) {
475 std::vector<SchedulerItem *> old_items;
476 ESP_LOGD(TAG,
"Items: count=%zu, pool=%zu, now=%" PRIu64, this->items_.size(), this->scheduler_item_pool_.size(),
480 while (!this->items_.empty()) {
483 LockGuard guard{this->lock_};
484 item = this->pop_raw_locked_();
487 SchedulerNameLog name_log;
488 bool is_cancelled = is_item_removed_(item);
489 ESP_LOGD(TAG,
" %s '%s/%s' interval=%" PRIu32
" next_execution in %" PRIu64
"ms at %" PRIu64
"%s",
490 item->get_type_str(), LOG_STR_ARG(item->get_source()),
491 name_log.format(item->get_name_type(), item->get_name(), item->get_name_hash_or_id()), item->interval,
492 item->get_next_execution() - now_64, item->get_next_execution(), is_cancelled ?
" [CANCELLED]" :
"");
494 old_items.push_back(item);
499 LockGuard guard{this->lock_};
500 this->items_ = std::move(old_items);
502 std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
513 if (this->to_remove_count_() >= MAX_LOGICALLY_DELETED_ITEMS) {
514 this->full_cleanup_removed_items_();
516 while (!this->items_.empty()) {
518 SchedulerItem *item = this->items_[0];
519 if (item->get_next_execution() > now_64) {
524 if (item->component !=
nullptr && item->component->is_failed()) {
525 LockGuard guard{this->lock_};
526 this->recycle_item_main_loop_(this->pop_raw_locked_());
534#ifdef ESPHOME_THREAD_MULTI_NO_ATOMICS
537 LockGuard guard{this->lock_};
538 if (is_item_removed_locked_(item)) {
539 this->recycle_item_main_loop_(this->pop_raw_locked_());
540 this->to_remove_decrement_();
546 if (is_item_removed_(item)) {
547 LockGuard guard{this->lock_};
548 this->recycle_item_main_loop_(this->pop_raw_locked_());
549 this->to_remove_decrement_();
554#ifdef ESPHOME_DEBUG_SCHEDULER
556 SchedulerNameLog name_log;
557 ESP_LOGV(TAG,
"Running %s '%s/%s' with interval=%" PRIu32
" next_execution=%" PRIu64
" (now=%" PRIu64
")",
558 item->get_type_str(), LOG_STR_ARG(item->get_source()),
559 name_log.format(item->get_name_type(), item->get_name(), item->get_name_hash_or_id()), item->interval,
560 item->get_next_execution(), now_64);
567 now = this->execute_item_(item, now);
569 LockGuard guard{this->lock_};
573 SchedulerItem *executed_item = this->pop_raw_locked_();
575 if (this->is_item_removed_locked_(executed_item)) {
577 this->to_remove_decrement_();
578 this->recycle_item_main_loop_(executed_item);
582 if (executed_item->type == SchedulerItem::INTERVAL) {
583 executed_item->set_next_execution(now_64 + executed_item->interval);
586 this->to_add_.push_back(executed_item);
587 this->to_add_count_increment_();
590 this->recycle_item_main_loop_(executed_item);
593 has_added_items |= !this->to_add_.empty();
596 if (has_added_items) {
597 this->process_to_add();
600#ifdef ESPHOME_DEBUG_SCHEDULER
610 LockGuard guard{this->lock_};
611 this->debug_verify_no_leak_();
615void HOT Scheduler::process_to_add() {
618 if (this->to_add_empty_())
620 LockGuard guard{this->lock_};
621 for (
auto *&it : this->to_add_) {
622 if (is_item_removed_locked_(it)) {
624 this->recycle_item_main_loop_(it);
629 this->items_.push_back(it);
630 std::push_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
632 this->to_add_.clear();
633 this->to_add_count_clear_();
635bool HOT Scheduler::cleanup_() {
639 if (this->to_remove_empty_())
640 return !this->items_.empty();
650 LockGuard guard{this->lock_};
651 while (!this->items_.empty()) {
652 SchedulerItem *item = this->items_[0];
653 if (!this->is_item_removed_locked_(item))
655 this->to_remove_decrement_();
656 this->recycle_item_main_loop_(this->pop_raw_locked_());
658 return !this->items_.empty();
660Scheduler::SchedulerItem *HOT Scheduler::pop_raw_locked_() {
661 std::pop_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
663 SchedulerItem *item = this->items_.back();
664 this->items_.pop_back();
671 WarnIfComponentBlockingGuard guard{item->component, now};
673 return guard.finish();
677bool HOT Scheduler::cancel_item_(Component *
component, NameType name_type,
const char *static_name,
uint32_t hash_or_id,
678 SchedulerItem::Type
type,
bool match_retry) {
679 LockGuard guard{this->lock_};
680 return this->cancel_item_locked_(
component, name_type, static_name, hash_or_id,
type, match_retry);
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 match_retry) {
688 if (name_type == NameType::STATIC_STRING && static_name ==
nullptr) {
692 size_t total_cancelled = 0;
694#ifndef ESPHOME_THREAD_SINGLE
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, match_retry);
707 if (!this->items_.empty()) {
708 size_t heap_cancelled = this->mark_matching_items_removed_locked_(this->items_,
component, name_type, static_name,
709 hash_or_id,
type, match_retry);
710 total_cancelled += heap_cancelled;
711 this->to_remove_add_(heap_cancelled);
715 total_cancelled += this->mark_matching_items_removed_locked_(this->to_add_,
component, name_type, static_name,
716 hash_or_id,
type, match_retry);
718 return total_cancelled > 0;
721bool HOT Scheduler::SchedulerItem::cmp(SchedulerItem *a, SchedulerItem *b) {
724 return (a->next_execution_high_ ==
b->next_execution_high_) ? (a->next_execution_low_ >
b->next_execution_low_)
725 : (a->next_execution_high_ >
b->next_execution_high_);
732void Scheduler::recycle_item_main_loop_(SchedulerItem *item) {
736 if (this->scheduler_item_pool_.size() < MAX_POOL_SIZE) {
738 item->callback =
nullptr;
739 this->scheduler_item_pool_.push_back(item);
740#ifdef ESPHOME_DEBUG_SCHEDULER
741 ESP_LOGD(TAG,
"Recycled item to pool (pool size now: %zu)", this->scheduler_item_pool_.size());
744#ifdef ESPHOME_DEBUG_SCHEDULER
745 ESP_LOGD(TAG,
"Pool full (size: %zu), deleting item", this->scheduler_item_pool_.size());
748#ifdef ESPHOME_DEBUG_SCHEDULER
749 this->debug_live_items_--;
754#ifdef ESPHOME_DEBUG_SCHEDULER
755void Scheduler::debug_log_timer_(
const SchedulerItem *item, NameType name_type,
const char *static_name,
758 if (name_type == NameType::STATIC_STRING && static_name !=
nullptr) {
759 validate_static_string(static_name);
763 SchedulerNameLog name_log;
764 const char *type_str = (
type == SchedulerItem::TIMEOUT) ?
"timeout" :
"interval";
765 if (
type == SchedulerItem::TIMEOUT) {
766 ESP_LOGD(TAG,
"set_%s(name='%s/%s', %s=%" PRIu32
")", type_str, LOG_STR_ARG(item->get_source()),
767 name_log.format(name_type, static_name, hash_or_id), type_str,
delay);
769 ESP_LOGD(TAG,
"set_%s(name='%s/%s', %s=%" PRIu32
", offset=%" PRIu32
")", type_str, LOG_STR_ARG(item->get_source()),
770 name_log.format(name_type, static_name, hash_or_id), type_str,
delay,
771 static_cast<uint32_t>(item->get_next_execution() - now));
778Scheduler::SchedulerItem *Scheduler::get_item_from_pool_locked_() {
779 if (!this->scheduler_item_pool_.empty()) {
780 SchedulerItem *item = this->scheduler_item_pool_.back();
781 this->scheduler_item_pool_.pop_back();
782#ifdef ESPHOME_DEBUG_SCHEDULER
783 ESP_LOGD(TAG,
"Reused item from pool (pool size now: %zu)", this->scheduler_item_pool_.size());
787#ifdef ESPHOME_DEBUG_SCHEDULER
788 ESP_LOGD(TAG,
"Allocated new item (pool empty)");
790 auto *item =
new SchedulerItem();
791#ifdef ESPHOME_DEBUG_SCHEDULER
792 this->debug_live_items_++;
797#ifdef ESPHOME_DEBUG_SCHEDULER
798bool Scheduler::debug_verify_no_leak_()
const {
801 size_t accounted = this->items_.size() + this->to_add_.size() + this->scheduler_item_pool_.size();
802#ifndef ESPHOME_THREAD_SINGLE
803 accounted += this->defer_queue_.size();
805 if (accounted != this->debug_live_items_) {
807 "SCHEDULER LEAK DETECTED: live=%" PRIu32
" but accounted=%" PRIu32
" (items=%" PRIu32
" to_add=%" PRIu32
809#ifndef ESPHOME_THREAD_SINGLE
813 static_cast<uint32_t>(this->debug_live_items_),
static_cast<uint32_t>(accounted),
814 static_cast<uint32_t>(this->items_.size()),
static_cast<uint32_t>(this->to_add_.size()),
815 static_cast<uint32_t>(this->scheduler_item_pool_.size())
816#ifndef ESPHOME_THREAD_SINGLE
818 static_cast<uint32_t>(this->defer_queue_.size())
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
const Component * component
Providing packet encoding functions for exchanging data with a remote host.
float random_float()
Return a random float between 0 and 1.
const char int const __FlashStringHelper * format
void retry_handler(const std::shared_ptr< RetryArgs > &args)
const char int const __FlashStringHelper va_list args
void HOT delay(uint32_t ms)
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.
constexpr uint32_t SCHEDULER_DONT_RUN