Current implementation with timer context:
This is the rule in which I use timer context…
var Item_timer_auto_off, Dedicated_timer;
console.info('Rule fired ... (Light Timer)');
Item_timer_auto_off = String(event.itemName) + '_timer_auto_off';
Dedicated_timer = String(event.itemName) + '_timer';
if (cache.private.exists(Dedicated_timer) === false || cache.private.get(Dedicated_timer).hasTerminated()) {
cache.private.put(Dedicated_timer, actions.ScriptExecution.createTimer(Dedicated_timer, time.ZonedDateTime.now().plusMinutes(items.getItem(Item_timer_auto_off).numericState), function (timer_context) {
items.getItem((timer_context)).sendCommand('OFF');
}, event.itemName));
} else {
cache.private.get(Dedicated_timer).reschedule(time.ZonedDateTime.now().plusMinutes(items.getItem(Item_timer_auto_off).numericState));
};
console.info('Rule finished ... (Light Timer)');
I have different switch items triggering the same rule by pressing wallswitches - in fact the rule could potentially be triggerd by one wallswitch while another timer is still running from another wallswitch that was pressed before.
That’s why I append the triggering item name with:
- “_timer_auto_off” to get a Number_Time item corresponding to the triggering item.
- “_timer” to get a timer name corresponding to the triggering item.
By that I avoid duplicating the rule for every wallswitch = avoid that timers conflict each other, if running in parallel.
This rule works perfectly well when using timer context.
I took this as a challenge and tried an alternative implementation without timer context:
var Item_switch, Item_timer_auto_off, Dedicated_timer;
console.info('Rule fired ... (Light Timer)');
Item_switch = event.itemName;
Item_timer_auto_off = String(event.itemName) + '_timer_auto_off';
Dedicated_timer = String(event.itemName) + '_timer';
if (cache.private.exists(Dedicated_timer) === false || cache.private.get(Dedicated_timer).hasTerminated()) {
cache.private.put(Dedicated_timer, actions.ScriptExecution.createTimer(Dedicated_timer, time.ZonedDateTime.now().plusMinutes(items.getItem(Item_timer_auto_off).numericState), function (timer_context) {
items.getItem(Item_switch).sendCommand('OFF');
}, undefined));
} else {
cache.private.get(Dedicated_timer).reschedule(time.ZonedDateTime.now().plusMinutes(items.getItem(Item_timer_auto_off).numericState));
};
console.info('Rule finished ... (Light Timer)');
I thought this could be done by using a variable “Item_switch” holding the triggering item name and using that variable inside the timer instead of using the timer context. It seemed to me so logical that this should work, but it doesn’t. Parallel timers conflict each other.
What’s wrong with that approach?
Is there a way to avoid timer context in this use case?