How to loop efficiently and/or randomize execution time?

End goal: I'd like a script to repeat with randomized execution time. (Currently it runs every n minutes.)

High level options:

  1. Have the macro repeat itself, and randomize repeats
  • Another method to randomize the time trigger

Since I don't know of a way to do #2, I tried #1 but couldn't find a way to do it efficiently (for CPU + battery).

Based on Peter's comment I tried a using an until/while loop with time calculations to repeat the script. But the Keyboard Maestro engine jumped to steady 10% CPU usage, even with the addition of a fixed 60 second delay.

Any ideas on more efficient ways to achieve this outcome (randomized execution time)?

Keyboard Maestro Engine is designed to be highly efficient when it is not processing a macro. So sitting idle, regardless of what triggers you have active, the engine should consume tiny amounts of Battery/Energy/CPU. Typical CPU usage will be well less than 1%.

But. Once you are executing a macro, regardless of what it is doing, neither efficiency nor extreme performance are primary design goals. So even doing a plain Pause action will cause an appreciable performance penalty. And while it would certainly be possible for it to be more efficient in the case where it has a single macro running sitting in a timed pause, it is not exactly a typical case.

The solution to your problem is to not leave the macro running. For this case, you clearly have no need for checking the next activation time more than once per minute, so trigger periodically once per minute and check if it is time to execute yet.

Macro “Start Random Script”:

  • Set variable nextExecutionTime to NOW() + (2+RAND(8)) * 60
  • Enable Macro “Check Random Script”

Macro “Check Random Script”:

  • Trigger periodically every 1 minute
  • If NOW() > nextExecutionTime Then
    • Disable Macro “Check Random Script”
    • Execute Macro “Run Random Script”
    • Execute Macro “Start Random Script” <-- optional repeat

Something like that.

1 Like

Thanks for the reply, Peter – I’ll check it out when I have some free time

This is working great, by the way. Thanks again, Peter. :thumbsup:

1 Like

Good. Mark the answer is "solved".