Hub slowed down by simple events collection over 3 iterations


Is this normal that this code below can take between 1 up to 10 seconds and even more sometimes to execute (whether it's with one or 3 iterations)? I added a time stamp before and after its execution to figure this out. Once these lines written, my hub would become painfully unresponsive and back to normal once commented out.

Here is my question: despite this instance involving only 3 devices, is it a known thing that such code would inherently take so much ressource or am I doing something wrong?

        logging("motion test is running and collecting events at $motionSensors")
        long deltaMinutes = noMotionTime * 1000 * 60   
        int s = motionSensors.size() 
        int i = 0

        def before = new Date()
        before.format("yyyyMMdd-HH:mm:ss.SSS", TimeZone.getTimeZone('UTC')) "Before the shit happens: ${before}"

        for(s != 0; i < s; i++) 
            // as soon as I would comment out this line below, the bug would become responsive again. 
          thisDeviceEvents = motionSensors[i].eventsSince(new Date(now() - deltaMinutes)).findAll{it.value == "active"} // collect motion events for each sensor
            events += thisDeviceEvents.size()
            events += thisDeviceEvents.size()

        def after = new Date()
        after.format("yyyyMMdd-HH:mm:ss.SSS", TimeZone.getTimeZone('UTC')) "AFTER the shit happened: ${after}"

What is the value of "noMotionTime"?

You are querying the events there but I can see for how far back you are going. The further you go back in time the longer it will take.

Makes sense indeed! However, the value is only 10 minutes.
I'm so much stuck with this that I have replaced this code with a collection made "manually" from the event handler directly and then it's a matter of working with time comparisons. It works, but it's not as elegant.

Hmmm, I have to admit, I have never used this function eventsSince

If you want to diagnose it even further, you could add some log statements within the for loop to see if it is a particular device that is causing the delay.

Here are some code suggestions:

For get s, i and thisDeviceEvents.

def myPeriod = new Date(now() - deltaMinutes)
motionSensors.each { sensor ->
    events += sensor.eventsSince(myPeriod).findAll{it.value == "active"}.size()

Thank you @bravenel. My question still remains, though. Was the lagging something to expect with my code and if yes, can someone try to teach me about this? I'd love to understand. This is really just a matter of curiosity and learning. :slight_smile: