Edit: Updates for OH 4
Please see Design Pattern: What is a Design Pattern and How Do I Use Them for a description of DPs.
Problem Statement
Frequently, when attempting to write generic rules, especially when applying Design Pattern: Associated Items, one may need to set a separate Timer for each Item.
Concept
Store the Timers into a Map or dict using the Item name as the key.
Example
Blockly
openHAB Rules Tools [4.1.0.0;4.9.9.9] provides a timer manager block.
See the docs for the library for more details. The block creates a TimerMgr in the given cache with the given name. It checks to see if a timer by the name “foo” already exists. If “reschedule if exists” is checked it will reschedule it and any blocks next to “run if already exists” are run. If the timer doesn’t exist, the blocks next to “run at scheduled time” will be run after the given “after”.
JS Scripting
openHAB Rules Tools Announcements provides a TimerMgr class.
var {TimerMgr} = require('openhab_rules_tools');
var tm = cache.private.get('timers', () => TimerMgr());
tm.check(event.itemName, time.toZDT('PT5M'), () => {
// do something
});
That one call to check
does the following:
- if there is a timer already for the given Item name it’s cancelled
- if there is not a timer a timer is created to go off in five minutes which calls “do something”.
check
also supports passing a boolean to have the timer rescheduled instead of cancelled and a second function that gets called when the timer already exists. See the link for details.
Rules DSL
Pay attention to the lines where the variable timers
is used.
import java.util.Map
val Map<String, Timer> timers = newHashMap
rule "Send alert if a door has been open for more than 60 minutes"
when
Member of Doors changed
then
// Always cancel the existing Timer
val timer = timers.get(triggeringItem.name)
timer?.cancel
timers.put(triggeringItem.name, null)
// Create a Timer if the door opened
if(triggeringItem.state == OPEN) {
timer.put(timerItem.name, createTimer(now.plusHours(1), [ |
Alert.sendCommand(triggeringItem.name + " is still open!")
])
}
end
Related Design Patterns
Design Pattern | How It’s Used |
---|---|
Design Pattern: Associated Items | Includes an example of this DP. |