Execute rule during certain period of time

How can I have the following rules only work between 10pm until 5am?

var Number counter = 0
var Number lastCheck = 0

rule "DenMotionLightOn"
when   
        Item FoyerMotion changed from CLOSED to OPEN 
then   
        counter = counter + 1 {
        sendCommand(DenLamp, 15)
        }
end

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

Hi,

I use the following statement:

var Number hour = now.getHourOfDay	
if ((hour >= 22)  || (hour <= 5)) {
      // ... do stuff here
} 

kind regards,
Patrik

@patrik_gfeller’s solution is the simplest solution.

Alternative solutions include setting up events on your Google Calendar and using the GCal Binding.

My preferred solution is posted here.

Thanks. I’ll check to see if it works tonight.

Could someone check this rule. It’s causing my light do go on all the time when there’s motion, when its supposed to just work between 10pm-5am.

rule “LateNightMotionLightsOn”
when
Item FoyerMotion changed from CLOSED to OPEN
then
if ((hour >= 22) || (hour <= 5 )) {
counter = counter + 1 {
sendCommand(DenLamp, 15)
sendCommand(LivingRoomLights, 15)
sendCommand(KitchenSinkLight, 15)
}}
end

I do have this command at the top of my file:
var Number hour = now.getHourOfDay

seems to be missing; try to put it directly in the rule as a 1st try - not sure if it works were you placed it.

You can also use

logInfo("heizung.rules","Hour: " + hour)

to check if the value is set correctly.

Thanks. I moved it down directly in the rule. Its not causing the light to go on right now.

Just to explain why moving the hour var down into the rule worked, your global vars and vals are only evaluated once when the rule is first loaded. So when it is at the top of the file, hour gets set to whatever hour it was when the rules file was loaded and it never changes. When you move it into the rule hour gets reset to the whatever hour it is when the rule executes, which is the behavior you want.

1 Like

Thanks for the explanation Rich. I just started using OpenHAB a few weeks ago. I’m trying to get it up and fully running to replace my vera home automation device. I appreciate trying to understand
the OpenHAB language instead of just cutting a pasting various rules.