@@ -47,7 +47,7 @@ struct recurrent_fn_t
4747
4848static recurrent_fn_t * rFirst =nullptr ;
4949static recurrent_fn_t * rLast =nullptr ;
50- static uint32_t rScheduleTarget = 0 ;
50+ static uint32_t rTarget ;
5151
5252// Returns a pointer to an unused sched_fn_t,
5353// or if none are available allocates a new one,
@@ -118,10 +118,13 @@ bool schedule_recurrent_function_us(const std::function<bool(void)>& fn,
118118
119119 item->mFunc = fn;
120120 item->alarm = alarm;
121- // if (!rScheduleTarget || rScheduleTarget > item.callNow.remaining())
122- // {
123- // rScheduleTarget = item.callNow.remaining();
124- // }
121+
122+ // prevent new item overwriting an already expired rTarget.
123+ const int32_t rRemaining = rTarget -millis ();
124+ if (!rFirst || (rRemaining >0 &&static_cast <uint32_t >(rRemaining) > item->callNow .remaining ()))
125+ {
126+ rTarget =millis () + item->callNow .remaining ();
127+ }
125128
126129 esp8266::InterruptLock lockAllInterruptsInThisScope;
127130
@@ -138,9 +141,12 @@ bool schedule_recurrent_function_us(const std::function<bool(void)>& fn,
138141return true ;
139142}
140143
141- uint32_t compute_scheduled_recurrent_grain ()
144+ uint32_t get_scheduled_recurrent_delay ()
142145{
143- return 0 ;
146+ if (!rFirst)return ~static_cast <uint32_t >(0 );
147+ // handle already expired rTarget.
148+ const int32_t rRemaining = rTarget -millis ();
149+ return (rRemaining >0 ) ?static_cast <uint32_t >(rRemaining) :0 ;
144150}
145151
146152void run_scheduled_functions ()
@@ -203,6 +209,7 @@ void run_scheduled_recurrent_functions()
203209 fence =true ;
204210 }
205211
212+ rTarget =millis () + current->callNow .remaining ();
206213recurrent_fn_t * prev =nullptr ;
207214// prevent scheduling of new functions during this run
208215auto stop = rLast;
@@ -241,6 +248,12 @@ void run_scheduled_recurrent_functions()
241248 {
242249 prev = current;
243250 current = current->mNext ;
251+ // prevent current item overwriting an already expired rTarget.
252+ const int32_t rRemaining = rTarget -millis ();
253+ if (rRemaining >0 &&static_cast <uint32_t >(rRemaining) > current->callNow .remaining ())
254+ {
255+ rTarget =millis () + current->callNow .remaining ();
256+ }
244257 }
245258
246259if (yieldNow)