OpenHAB is an opensource homeautomationsoftware. In this article, I will explain how to add a random delay to an action in openHAB using rules. The whole concept is known as Jitter.

My goal

My goal was it to turn on a device with a random delay using openHAB rules. It was pretty clear to me that I was unable to use openHAB’s GUI rule editor.

My solution

With a bit of knowledge of Java and a bit of reading I was able to create this solution:

rule "LampeVerzoegertAn"
when
	Time cron "0 54 20 1/1 * ? *"
then
        var int randomTime = (new java.util.Random).nextInt(20,125)
	    logInfo("org.openhab","Setting random lights timer to " + randomTime + "seconds.")
	    tRandomLights = createTimer(now.plusSeconds(randomTime)) [|
                MyLight.sendCommand(ON)
            ]
end

The line Time cron "0 54 20 1/1 * ? *" in the when-Block tells openHAB, that we’re creating a time-based rule. This rule will get triggered at 20:54, that means, that the earliest time the device will turn on is 20:54. The line var int randomTime = (new java.util.Random).nextInt(20,125) defines a variable called randomTime of the type int. In the brackets we can define the minimum delay (in this case 20 seconds) and the maximum delay(in this case 125 seconds, around two minutes). In the next step, the code will generate a log message. The line tRandomLights = createTimer(now.plusSeconds(randomTime)) [| creates a new timer with the delay of randomTime. After the [| bracket-block is the needed code. In this case, I will be turning on the Item (Attention, not a device!), called MyLight. In the last step, you will have to close the block with a bracket again.

With this code I was able to create the wanted behaviour.