Timeouts for Tickers, MultiTasking etc.

My first post, so please be tolerant.

This is more of an observation requesting comment, rather than a problem.

I’m working on a new project that involves multiple sensors (LDR x 4, PT100/MAX31865 x 2, DS1820, Rotary encoders and more) together controlling a PWM motor controlled, plus web support. The hardware is an ESP8266 for mostly the web stuff, plus an Arduino Pro mini as a port expander, the two communicate over SDA/SDC.

Some sensors need reading often, other less often. To control all the concurrent sensors, comms and control output, I’ve been looking at various timer libraries such as Ticker, Task etc.
In all the examples within those libraries, various timers are shown with nice round numbers eg 250ms, 500ms, 1000ms. These all tend to fire off at the same time repeatedly, in this case once every second, all three go off.

From my experience working with an RTOS, I know that this is not a nice thing – it’s much better if processes spread out within the available CPU time, this stops any queues building, and reduces stress of time crucial processing.

So, my solution, is to always use unique prime numbers that are close to the desired timeouts. This will cause a natural spreading of the processes, with only occasional and short term bunching.
Below is a sample BlinkWithoutDelay I’ve written to demonstrate this. If you let it run for a while, you’ll see the LED blinking with a seemingly random and varying nature. Similarly, the timing of the serial output shows a stuttered behaviour (a desired thing in this case).

#include <Arduino.h>

#define onTimeout(timer, period)         \
  static unsigned long timer = millis(); \
  for (unsigned long now = millis(); (now - timer) > (unsigned long)period; timer = now)

void setup()
{
  Serial.begin(115200);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
  onTimeout(timerA, 503)
  {
    Serial.println("TimA");
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
  }
  onTimeout(timerB, 1009)
  {
    Serial.println("TimeB");
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
  }
  onTimeout(timerC, 2003)
  {
    Serial.println("TimerC");
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
  }
}

So, what does anyone think about this – always use unique prime numbers for repeating non-time critical timeouts.

Yes. I always use that, since I heard of it. My once-per-minute status messages are 60013ms apart.

Another approach is to interleave the actions deliberately rather than rely on time. For example read YYY in the next iteration of loop() after every 4th read of XXX

I used that approach in a project where motor speed was controlled by PID and the speed setting was being received by wireless. I only checked the wireless for a new message after the PID calculation was complete as there would then be plenty of time to get the data from the wireless module before the next PID calculation was needed.

...R