Hi Rich,
Thanks for the response - Yes unfortunately I am using TimerMgr across multiple scripts, requiring the shared cache. I am using private for those which only are accessed by one script.
This post explains why I originally made this architectural change, to align things around ‘events’:
The TimerMgr function you created, and the availability of the shared cache based timers, made my rules super-simple, and they have worked wonderfully ever since 2023!!!
After I posted my earlier reply in this thread last night, I did further testing, and found that in fact those additional lines I added were junk, and whilst it got me past the error, it didn’t make for a properly working TimerMgr under the shared cache on OH 5.2.1.
Which then got me thinking - could there be an option for a Rules Tools to work against the Shared Cache, so I don’t need to add hundreds of lines of code back into my scripts…
So I cobbled the following together last night, again with significant help from Gemini. It actually seemed to work ok, across a wide variety of scenarios, and edge-cases (Well those that I could think of last night anyway). I will be in a position to come back and have a deeper look at this next week, but in the meantime would be interested in your general thoughts on this approach, as I am somewhat out of my swimlane here !!
They are architecturally quite diverse, but they appear to be functionally equivalent. I know there is some ‘smoke and mirrors’ in there however (e.g. ‘name’ you pass when creating a timer is really just a prefix, not the actual instance). Also the ‘key’ (6th Parameter) is accepted, but ignored when using the timers.check()
/etc/openhab/automation/js/node_modules/test_rules_tools/index.js
module.exports = {
get sharedTimerMgr() {
console.warn('require SharedTimerMgr instead of sharedTimerMgr and use new SharedTimerMgr().');
return require('./SharedTimerMgr.js');
},
get SharedTimerMgr() {
return require('./SharedTimerMgr.js').SharedTimerMgr;
}
}
/etc/openhab/automation/js/node_modules/test_rules_tools/package.json
{
"name": "test_rules_tools",
"version": "1.0.0",
"description": "Custom shared timer utility for openHAB 5.2.1+ JS Scripting, based on the Original openhab_rules_tools TimerMgr by Rich Koshak",
"main": "index.js",
"author": "Glen McGeachen+Gemini",
"license": "EPL-2.0"
}
/etc/openhab/automation/js/node_modules/test_rules_tools/SharedTimerMgr.js
/**
* SharedTimerMgr - Thread-safe multi-rule timer manager for openHAB 5.2+ (GraalVM JS)
* Uses native Java timers stored in cache.shared with full backward-compatibility support.
*/
class SharedTimerMgr {
/**
* @param {string} cacheNamespace - Namespace key for cache.shared (e.g. 'gate_tm')
*/
constructor(cacheNamespace = 'default_tm') {
this.namespace = cacheNamespace;
}
_getKey(timerName) {
return `${this.namespace}_${timerName}`;
}
/**
* Check, create, or reschedule a shared timer.
*
* @param {string} timerName - Unique identifier for the timer within this namespace
* @param {number|string|time.ZonedDateTime|null} duration - Seconds (number), ISO duration ('PT10S'), or ZonedDateTime / string representation. If 0/null, cancels timer.
* @param {function} callback - Callback executed on expiration
* @param {boolean} [reschedule=true] - Whether to reschedule if timer is already active
* @param {function} [onReschedule=null] - Optional callback executed if rescheduled
*/
check(timerName, duration, callback, reschedule = true, onReschedule = null) {
// 1. Always enforce the internal namespaced key (ignore any 6th legacy parameter)
const key = this._getKey(timerName);
// 2. Cancellation: 0, '0', null, or undefined
if (duration === 0 || duration === '0' || duration === null || duration === undefined) {
return this.cancel(timerName);
}
let targetTime;
// 3. Convert duration or timestamp format into ZonedDateTime safely
if (typeof duration === 'number') {
targetTime = time.ZonedDateTime.now().plusSeconds(duration);
} else if (typeof duration === 'string') {
if (!isNaN(duration)) {
targetTime = time.ZonedDateTime.now().plusSeconds(Number(duration));
} else if (duration.startsWith('P') || duration.startsWith('p')) {
// Parse ISO-8601 Duration string (e.g. "PT10S", "PT15M")
targetTime = time.ZonedDateTime.now().plus(time.Duration.parse(duration));
} else {
// Parse ISO ZonedDateTime / LocalDateTime string directly (e.g. schedtime.toString())
targetTime = time.ZonedDateTime.parse(duration);
}
} else {
targetTime = duration;
}
// 4. Safely convert to Java ZonedDateTime across GraalVM polyglot boundary
let javaTargetTime = targetTime;
if (targetTime && typeof targetTime.toInstant === 'function') {
javaTargetTime = java.time.ZonedDateTime.parse(targetTime.toString());
}
let existingTimer = cache.shared.get(key);
if (existingTimer !== null && existingTimer !== undefined && !existingTimer.hasTerminated()) {
if (reschedule) {
existingTimer.reschedule(javaTargetTime);
if (typeof onReschedule === 'function') onReschedule();
}
return;
}
// 5. Create native Java timer stored in openHAB cache.shared under the namespaced key
let newTimer = actions.ScriptExecution.createTimer(javaTargetTime, () => {
try {
if (typeof callback === 'function') callback();
} finally {
cache.shared.remove(key);
}
});
cache.shared.put(key, newTimer);
}
/**
* Cancel an active timer.
* @param {string} timerName
* @returns {boolean} True if an active timer was found and canceled
*/
cancel(timerName) {
const key = this._getKey(timerName);
let existingTimer = cache.shared.get(key);
if (existingTimer !== null && existingTimer !== undefined && !existingTimer.hasTerminated()) {
existingTimer.cancel();
cache.shared.remove(key);
return true;
}
return false;
}
/**
* Check if a timer is currently active.
* @param {string} timerName
* @returns {boolean}
*/
hasTimer(timerName) {
const key = this._getKey(timerName);
let existingTimer = cache.shared.get(key);
return existingTimer !== null && existingTimer !== undefined && !existingTimer.hasTerminated();
}
}
module.exports = { SharedTimerMgr };
And a sample of a pair of test scripts I have used to test the check, cancel, and has timer across scripts, saves of the scripts while running, including using the legacy cancel approach from ‘check’:
//testtimerule1
var { SharedTimerMgr } = require('test_rules_tools');
var timers = new SharedTimerMgr('test_gate_tm');
console.info("=== [testtimerule1 Execution] ===");
// 1. Channel 1171: 10-second timer using ISO duration string ('PT10S')
var item1 = "CBUSTestChan1171_LightChannel";
var timer1Name = item1 + "_off_tm";
items.getItem(item1).sendCommandIfDifferent("ON");
timers.check(
timer1Name,
"PT10S", // ISO-8601 duration string
() => {
console.info(">>> [CALLBACK 1] 10s Timer Expired! Turning off " + item1);
items.getItem(item1).sendCommandIfDifferent("OFF");
},
true,
() => console.info(">>> [RESCHEDULE 1] " + timer1Name + " rescheduled for 10s!"),
timer1Name // 6th parameter ignored
);
// 2. Channel 0170: 15-second timer using ZonedDateTime object
var item2 = "CBUSTestChan0170_LightChannel";
var timer2Name = item2 + "_off_tm";
items.getItem(item2).sendCommandIfDifferent("ON");
timers.check(
timer2Name,
time.ZonedDateTime.now().plusSeconds(15), // ZonedDateTime target object
() => {
console.info(">>> [CALLBACK 2] 15s Timer Expired! Turning off " + item2);
items.getItem(item2).sendCommandIfDifferent("OFF");
},
true,
() => console.info(">>> [RESCHEDULE 2] " + timer2Name + " rescheduled!"),
timer2Name // 6th parameter ignored
);
console.info("Status " + timer2Name + " (Initial ZDT):", timers.hasTimer(timer2Name) ? "ACTIVE" : "INACTIVE");
// 3. Cancel Timer 2 using legacy method
console.info("Cancelling " + timer2Name + " using legacy check(0)...");
timers.check(timer2Name, 0, null, false, null, timer2Name);
console.info("Status " + timer2Name + " (Post-Cancel):", timers.hasTimer(timer2Name) ? "ACTIVE" : "CANCELED");
// 4. Re-schedule Timer 2 using stringified ZonedDateTime ISO string
console.info("Scheduling " + timer2Name + " again using ZDT string format...");
var schedTime = time.ZonedDateTime.now().plusSeconds(20);
timers.check(
timer2Name,
schedTime.toString(), // Stringified ZonedDateTime ISO timestamp
() => {
console.info(">>> [CALLBACK 2 - REARMED] 20s String Timer Expired! Turning off " + item2);
items.getItem(item2).sendCommandIfDifferent("OFF");
},
true,
() => console.info(">>> [RESCHEDULE 2] " + timer2Name + " rescheduled!"),
timer2Name // 6th parameter ignored
);
console.info("Status " + timer1Name + " (10s PT10S):", timers.hasTimer(timer1Name) ? "ACTIVE" : "INACTIVE");
console.info("Status " + timer2Name + " (20s ZDT String):", timers.hasTimer(timer2Name) ? "ACTIVE" : "INACTIVE");
var { SharedTimerMgr } = require('test_rules_tools');
var timers = new SharedTimerMgr('test_gate_tm');
var timer1Name = "CBUSTestChan1171_LightChannel_off_tm";
var timer2Name = "CBUSTestChan0170_LightChannel_off_tm";
console.info("=== [testtimerrule2 Execution] ===");
if (timers.hasTimer(timer1Name) || timers.hasTimer(timer2Name)) {
console.info("Found active timers from Rule 1. Cancelling both...");
// Cancel Timer 1 using legacy .check(name, 0, ...)
timers.check(timer1Name, 0, null, false, null, timer1Name);
// Cancel Timer 2 using direct .cancel(name)
timers.cancel(timer2Name);
console.info("Post-cancel status " + timer1Name + ":", timers.hasTimer(timer1Name) ? "ACTIVE (FAIL)" : "CANCELED (SUCCESS)");
console.info("Post-cancel status " + timer2Name + ":", timers.hasTimer(timer2Name) ? "ACTIVE (FAIL)" : "CANCELED (SUCCESS)");
} else {
console.info("No active timers found. Triggering testtimerule1 now...");
rules.runRule("testtimerule1");
}
I have been through a few versions of these last night, and managed to get clean runs working. (My biggest issue was an old expire timer I had left on an test item, that I forgot about !! - Drove me crazy for a while).
Cheers