Behavior of "timer.setInterval(000L, function1)"

Hi, just a question for my understanding:

I have two functions xxx and yyy that need to run every second.

  • Is it better performance/stability wise to call each of them in its own “timer.setInterval(1000L, xxx)”, “timer.setInterval(1000L, yyy)” or is it better to combine both functions into one function aaa called by a single “timer.setInterval(1000L, aaa)”?
  • is every “timer.setInterval(1000L, xxx)” resulting in a separate and individual scheduling action or does Blynk already combine those functions that have the same interval?
  • is there a “Blynk preferred” approach to the above?

thanks.

This is not really a Blynk issue as Blynk is not the deciding factor in how the processor works… which is not as a true multitasking process. Nor is Blynk the author of the SimpleTimer base on which BlynkTimer is made, so this “prefered timing” approach works just as well with non-Blynk code and SimpleTimer.

But back to the question… each timer process is handled by the MCU splitting it’s time between concurrent tasks, just very fast. So the more happening “at the same time” the more chance for things being bogged down.

So in your example, it is best to have one timer running every command you want ran at that time (consecutively of course, just like normal).

This is why it is important to have timers staggered so as not to end up running concurrently at times…

For example a 1 second timer will coincide with any and all other timers that run in combinations of full seconds… 2 second timer will coincide every 2, 4, 6, 8… seconds, 1.5 second timer would coincide every 3, 6, 9, 12… seconds, and of course the 2 and 1.5 second timer would also coincide every 6, 12 seconds, etc…

Two ways of dealing with that are stagger the timers by enough offset to avoid such coinciding times as much as possible…

timer.setInterval(1010, stuff1);
timer.setInterval(2028, stuff2);
timer.setInterval(5033, stuff3);

Leaving each timer running at odd times, but generally missing each other, provided their called function tasks don’t take long enough to allow overlap with next timer.

Or start each timer with a small delay at their initialisation…

timer.setInterval(1000, stuff1);  // Every second
delay(20);
timer.setInterval(1000, stuff2);  // Every second
delay(20);
timer.setInterval(5000, stuff3);  // Every 5 seconds

The keeps each timer at its predictive interval (if that is a factor) but always 20 to 40 ms offset from the prior ones. Again, adjust the delay to account for the time it takes to run the called function.

Beware, there will always be some case of overlap with running code… the key it to minimise that as best abled, particularly with time sensitive activities like Stepper Motors or Ultrasonic Sensors, etc.

1 Like

thanks Gunner for your prompt and instructive feedback.