[SOLVED] Add a timer to a rule

Hello guys,
I’d like to set a timer (for about 5min) at the marked line in the code below. How can I do that? It would also be very nice if you could explain your solution because I’m very new in all this and I’d like to understand it :smile:

var DecimalType hue 
var PercentType sat 
var PercentType brigth 
var HSBType licht

rule "Alarm"

when
Item alarm_aus received command or 
Item Srv_Temperatur changed

then 

    Temp_update.postUpdate(new DateTimeType())

        if (alarm_aus.state == OFF) {

                hue = new DecimalType (240)
                sat = new PercentType (30)
                brigth = new PercentType (60)
                licht = new HSBType(hue,sat,brigth)

                Srv_HueColor.sendCommand(licht)

*********************************Timer here**************************************

        }
        else {

          code goes on....

end

Thanks for your help!

Try using createTimer.
Example:

createTimer(now.plusMinuets(5), [ |
                //do stuff
            ])   

Hey,

will the “stuff” be executed while the timer is counting down or will the “stuff” be executed after the timer has finished?

Here’s a link to help explain some of the rules using design patterns. At the bottom, you will see additional links that may help for future rules. Rich does a good job explaining everything in detail, hope you find it helpful. If this particular design pattern does not fit your needs then do a search on the forum (key word design pattern) and you should be able to find many other great tutorials that will walk you thru how they work.

EDIT: I forgot to add the link.:upside_down_face:

1 Like

The stuff will execute after the timer.

Here is a motion rule example that will check the condition of a timer and reset/cancel.

var Timer myTimer = null
rule "Motion OFF"
when
    Item Motion changed from OFF
then
    if (myTimer === null) {
        if  (Motion.state == ON) {
            myTimer = createTimer(now.plusSeconds(60), [ |
                if (Motion.state == ON){
                //do stuff
                }
            ])   
        }
    }
end

rule "BACK FROM ON"
when
    Item Motion changed from ON
then
    myTimer.cancel
    myTimer = null
end
1 Like

Maybe consider to do it more straight forward:

var Timer myTimer = null
rule "Motion"
when
    Item Motion changed
then
    myTimer?.cancel
    if(Motion.state == ON) 
        myTimer = createTimer(now.plusSeconds(60), [ |
            //do stuff
        ])   
end

Hi, I used the, in my opinion, simplest way:

createTimer(now.plusMinutes(2), [ | ]

But thanks for your help!