[Solved] Limit execution of rule to certain times

Hi all,

I’m using a rule to turn my water fountain to ON when a motion sensor detected motion three times.

import org.openhab.core.library.types.*
import org.openhab.core.persistence.*
import org.openhab.model.script.actions.*
import org.java.math.*
import org.joda.time.*

var Number counter = 0
var Number lastCheck = 0

rule "Fountain ON" //when motion is detected 3 times

when   
        Item FibEye1_Motion_C changed from CLOSED to OPEN
then   
        counter = counter + 1
        if(counter>2) {
                sendCommand(Licht_UG_Fountain, ON)
        }
ItemFountainCount.postUpdate(counter) //show counter in GUI
end

rule "Fountain OFF"
when   
        Time cron "0 * * * * ?"
then
        if(lastCheck == counter) {
                counter = 0
                lastCheck = -1;
                sendCommand(Licht_UG_Fountain, OFF)
        } else {
                lastCheck = counter
       }
end

This works fine since a couple of month.

Now I would like to limit this to a certain time, for example 9AM to 10PM.

So I’ve put around the rule:

    import org.openhab.core.library.types.*
    import org.openhab.core.persistence.*
    import org.openhab.model.script.actions.*
    import org.java.math.*
    import org.joda.time.*

    var Number counter = 0
    var Number lastCheck = 0

    rule "Fountain ON" //when motion is detected 3 times

    when   
            Item FibEye1_Motion_C changed from CLOSED to OPEN
    then   
    if ((now.getHourOfDay() < 22) || (now.getHourOfDay() > 8)) {
            counter = counter + 1
            if(counter>2) {
                    sendCommand(Licht_UG_Fountain, ON)
            }
}
    ItemFountainCount.postUpdate(counter) //show counter in GUI
    end

    rule "Fountain OFF"
    when   
            Time cron "0 * * * * ?"
    then
   if ((now.getHourOfDay() < 22) || (now.getHourOfDay() > 8)) {
            if(lastCheck == counter) {
                    counter = 0
                    lastCheck = -1;
                    sendCommand(Licht_UG_Fountain, OFF)
            } else {
                    lastCheck = counter
       }
 }
 end

This doesn’t work at all. The fountain is still doing its job all day. What are I’m doing wrong?

Thanks for any hint.

You may have to relook at your logic for the time check. At the moment it is checking if the current time is less than 10pm OR it is greater than 8am. As any time after midnight is less than 10pm, your code will execute between 12am to 10pm.

To get it to work between 9am and 10pm, you could do:

if ((now.getHourOfDay() >= 9) && (now.getHourOfDay() <22)) {

2 Likes

Thanks a lot, that did the trick.
That’s the problem if you are only a “copy from others” and “paste into yours” programmer :grin:

:smile: