Creating a Light Timer in OH3

RPi 4 running 3.2.0.M2

Trying to use the Timer action to turn off a light that has been turned on by a door sensor.
I have a this rule that turns on the light

rule    "Front Door Light Timer"
when 
    Item ZWaveNode023FrontDoor_Doorsensor changed from CLOSED to OPEN
then 
    ZWaveNode020ZEN24HallwayLight_Dimmer.sendCommand(ON)
end  

Can I combine the timer to turn it off into the same rule?
I don’t want to use an Expiration timer because I’d like the light to stay on if it is turned on by a means other than the door sensor.

Thanks
Brian

Sure.

Just use a timer in the rule:

var Timer tFrontDoor = null // initialize at the beginning of the file

rule    "Front Door Light Timer"
when 
    Item ZWaveNode023FrontDoor_Doorsensor changed from CLOSED to OPEN
then
    val Integer iSeconds = 120 // timeout  for Light to turn off
    if(tFrontDoor === null && ZWaveNode020ZEN24HallwayLight_Dimmer.state == 0) {
        ZWaveNode020ZEN24HallwayLight_Dimmer.sendCommand(ON)
        tFrontDoor = createTimer(now.plusSeconds(iSeconds). [|
            ZWaveNode020ZEN24HallwayLight_Dimmer.sendCommand(OFF)
            tFrontDoor = null
        ]) 
    } else if(tFrontDoor !== null && ZWaveNode020ZEN24HallwayLight_Dimmer.state != 0) {
        tFrontDoor.reschedule(now.plusSeconds(iSeconds))
    }
end

This rule will only start the Timer, if the Light is OFF (as it’s a dimmer, we have to test if it’s 0).
Furthermore the rule will reschedule the timer only if the timer is running and the light is ON (i.e. not 0).

Jruby’s syntax:

A quick way of doing it is this:

changed ZWaveNode023FrontDoor_Doorsensor, from: CLOSED, to: OPEN do 
  ZWaveNode020ZEN24HallwayLight_Dimmer.on
  after(2.minutes) { ZWaveNode020ZEN24HallwayLight_Dimmer.off }
end

What I do with mine is this extra logic:

  • Cancel the timer when the light is turned off. For example, someone opened the door, but wants to be in there for longer than 2 minutes and rather than getting the light turning off, he’d turn it off on the wall (which will cancel the timer), then turn it back on (which then won’t have any timer started)

Very helpful replies!
Thanks to both of you.!

Don’t be frightened to have more than one rule.
For example, when the door opens, turn on the light (if needed). You might kill any existing timer, but otherwise do not start timing.
When the door closes, begin the off-timer.

It now works like an extended fridge door light, always on when door open and goes off after it is closed. You choose the logic to suit your need.

You can do all that in one rule, but sometimes it is easier to understand separated functions.