I was looking around in java and there is a possibility to create random numbers. the code below is working and is created for testing purposes. I’ve put it here perhaps it could be interesting for others.
It is just triggered every minute and then a random timer is triggered to send a command to a wall switch toggling on off wich is controlled by the boolean onoff.
import java.util.Random;
var boolean onoff = false
rule "TestRandomOn"
when
Time cron "0 0/1 * 1/1 * ? *" // every minute
then {
logInfo("TestRandomOn",'Time cron triggered')
// Obtain a number between [0 - 59].
if (onoff == false) {
var Random rand= new Random();
var int randnum = rand.nextInt(60)
logInfo("TestRandomOn","randnum initialised :" + randnum)
createTimer(now.plusSeconds(randnum),[|
logInfo("TestRandomOn","Timer expired :" + randnum + " and onoff = false")
WallPlug.sendCommand(ON)
logInfo("TestRandomOn","Wallplug switched on")
onoff = true
])
}
}
end
rule "TestRandomOff"
when
Time cron "0 0/1 * 1/1 * ? *" // every minute
then {
logInfo("TestRandomOff",'Time cron triggered')
// Obtain a number between [0 - 59].
if (onoff == true) {
var Random rand= new Random();
var int randnum = rand.nextInt(60)
logInfo("TestRandomOff","randnum initialised :" + randnum)
createTimer(now.plusSeconds(randnum),[|
logInfo("TestRandomOff","Timer expired :" + randnum + " and onoff = true")
WallPlug.sendCommand(OFF)
logInfo("TestRandomOff","Wallplug switched off")
onoff = false
])
}
}
end
Hope it is useful…
When doing the same approach but with the math.random class this is giving an error ‘An error occurred during the script execution: Could not invoke method: org.joda.time.DateTime.plusSeconds(int) on instance’.
Below the code:
var boolean onoff = false
var int rand
rule "TestRandomOn"
when
Time cron "0 0/1 * 1/1 * ? *" // every minute
then {
logInfo("TestRandomOn",'Time cron triggered')
// Obtain a number between [0 - 59].
if (onoff == false) {
rand= Math.round(Math.random() * 60)
logInfo("TestRandomOn","randnum initialised :" + rand)
createTimer(now.plusSeconds(rand),[|
logInfo("TestRandomOn","Timer expired :" + randnum + " and onoff = false")
WallPlug.sendCommand(ON)
logInfo("TestRandomOn","Wallplug switched on")
onoff = true
])
}
}
end
rule "TestRandomOff"
when
Time cron "0 0/1 * 1/1 * ? *" // every minute
then {
logInfo("TestRandomOff",'Time cron triggered')
// Obtain a number between [0 - 59].
if (onoff == true) {
rand= Math.round(Math.random() * 60)
logInfo("TestRandomOff","randnum initialised :" + rand)
createTimer(now.plusSeconds(rand),[|
logInfo("TestRandomOff","Timer expired :" + randnum + " and onoff = true")
WallPlug.sendCommand(OFF)
logInfo("TestRandomOff","Wallplug switched off")
onoff = false
])
}
}
end
Looking further the Math.random is using more processing power as java.util.Random so it would be nice to have an explanation why the math.random is generating an error. Nevertheless I’m using the first java.util.Random and it’s working fine.
Thanks anyone for the feedback.