If with a time delay

I have a string, and when that string get an update to the value “A” - then I would like a rule that checks if the stings get an update to value “B” - If the string does not get an update to the value “B” within 40 seconds then I would like to execute: sendCommand(Relay_Switch, “OFF”).

The problem is that I have no idea how to write such a script, can any one help me?

Break the job down.

Fire a rule from string update.
Check to see if value is “A”, if so start (or restart) a timer.
Else
Check to see if value is “B”, if so is the timer running, if so do the task.

You’ll need to set up a global variable to hold the timer so that it is visible to different runs of the same rule.

The timer doesn’t need to do anything, except null itself on completion.

var Timer timer = null

rule "timmer string"
when
    Item timmerstring changed to "A"
then
    if (timer === null) {
        timer = createTimer(now.plusSeconds(40), [ |
            if (timerstring.state.toString != "B") {
                Relay_Switch.sendCommand(OFF)
                timer = null
            }
        ] )
    }
end
var Timer timer = null                                               // define a timer

rule "timmer string"
when
    Item timmerstring changed                                        // Item changed
then
    if (timmerstring.state.toString == "A" && timer === null)        // String = "A"? Timer not started?
        timer = createTimer(now.plusSeconds(40), [ |                 // Create the timer
            Relay_Switch.sendCommand(OFF)                            // switch off and
            timer = null                                             // reinitialize timer
        ] )
    else if (timmerstring.state.toString == "B" && timer !== null) { // String is "B" and timer started
        timer.cancel                                                 //  stop timer and
        timer = null                                                 // reinitialize timer
    }
end

Timer has to be cancelled, because the string can change more than once in 40 seconds!