This is a problem in the language. There is a similar problem in Python as well. Without going into a whole lot of detail, unlike in Rules DSL where each lambda function that gets passed to the timer gets a copy of the current set of variables, in JavaScript the lambda gets a pointer to the actual variable.
And because the context gets reused for every call to the script action, the event variable gets reused.
Combine those two and what you end up with is event.itemName in your Timer will show you what ever item most recently triggered the rule, not the name of the item that triggered the rule when the Timer was created.
To avoid this you need to “fix” the state of the variables before you create the function that gets passed to the timer so that it gets a copy instead of the pointing to the “real” events varaible.
Based on my research the “JavaScript” way to do this is through function generators.
this.OPENHAB_CONF = (this.OPENHAB_CONF === undefined) ? java.lang.System.getenv("OPENHAB_CONF") : this.OPENHAB_CONF;
load(OPENHAB_CONF+'/automation/lib/javascript/community/timerMgr.js');
load(OPENHAB_CONF+'/automation/lib/javascript/community/timeUtils.js'); // you don't need this import
this.ZonedDateTime = (this.ZonedDateTime === undefined) ? Java.type("java.time.ZonedDateTime") : this.ZonedDateTime;
var log = Java.type("org.openhab.core.model.script.actions.Log");
// Only create a new manager if one doesn't already exist or else it will be wiped out each time the rule runs
this.tm = (this.tm === undefined) ? new TimerMgr() : this.tm;
log.logWarn("Routinen", "Routine "+ event.itemName +" activated. - Time: " + event.itemState );
var timerFuncGenerator = function(itemName) {
return function() {
log.logWarn("Test", "Timer " + event.itemName + " ended");
}
}
this.tm.check(event.itemName,
event.itemState,
timerFuncGenerator(event.itemName)
);
Another approach, which would require changes to timerMgr itself, might be to use createTimerWithArguments
instead of createTimer
but that is on my long and growing list of things to do.