Countdown timer light switches

I’m looking for a simple way to implement a countdown timer to turn off a tp-link light switch. The trigger would be when the switch is turned on. I’d ljke the timer to count down a set period of time, say 1 hour, and then turn the switch off. I’ve tried using the expiration metadata tag but it is not consistent in its behavior as far as I can see.

Is there a ‘best practice’ approach to a countdown timer that I could implement through the OH3 gui at this point? I’m not that familiar with scripting and as a rule since the OH3 release I’ve been trying to keep my config as much through the gui as possible. Thoughts?

Any help is much appreciated, thanks.
(OH3 on RPI4 with openhabian)

I only use the expire in the metadata and it works fine.
Why are you saying it is inconsistent?
The only reason it would be inconsistent is the item is getting updated and if that happens the timer starts again.

You’d use a rule, which you can implement via GUI. Blockly is the most “UI friendly”, but not yet incorporating timing so no good here. Your choice of other scripting language.

I found that with short time intervals (e.g., a minute), my z-wave light switches would work reliably with the OH3 expiration timer defined in the metadata, but not for long intervals (e.g., an hour). I assumed that it had something to do with the zwave binding somehow updating the switch item state, thereby resetting the timer, but I never really figured it out exactly. In any case, using the expiration timer on a zwave switch was not reliable for me. Perhaps this is similar to your experience.

So the alternative is to write a rule. In OH3 I use ECMA javascript because you can define global variables within the UI, which is handy for timer functions.

Thanks all for the comments. I found a few other posts on implementing a simple timer and came up with the following javascript (not mine, but tweaked a bit) that works fine when used with an OH3 rule created via the gui.

Any thoughts on how best to make this more generic? I’d like to use this rule across several items with a minimum of changes if possible.

Cheers

var logger = Java.type(‘org.slf4j.LoggerFactory’).getLogger(‘org.openhab.rule.’ + ctx.ruleUID);
var ScriptExecution = Java.type(“org.openhab.core.model.script.actions.ScriptExecution”);
var ZonedDateTime = Java.type(“java.time.ZonedDateTime”);
var TimerMinutes = 60;
var Item = “LivingRoomFan_Power”;

if (this.timer != undefined) {
this.timer.cancel();
}

function turnOff() {
events.sendCommand(Item, OFF);
logger.info(Item +" Expire Rule after “+TimerMinutes +” minutes")
this.timer = undefined;
}

this.timer = ScriptExecution.createTimer(ZonedDateTime.now().plusMinutes(TimerMinutes), turnOff);