How do I stop a runaway timer?

@rule("test1")
@when("System started")
def test(event):  
    def timer():
        ScriptExecution.createTimer(DateTime.now().plusSeconds(1), timer)
        test.log.info("Hello") 
    ScriptExecution.createTimer(DateTime.now().plusSeconds(1), timer)

Once this timer runs… I can’t find a way to stop / remove it other than editing the code and then restarting openhab

Multiple reloading of this script will result in the creation of one timer for each reload, so over time I end up with lots of timers running. Try this out by changing “Hello” to Hello1 then save the script, then rename to Hello2, save, etc.

Is there a way to stop them other than an openhab restart?

I see this was discussed here Timers not cancelled when rule reloaded

So in short, no other way but restarting openhab, it seems?

The above script is obviously an oversimplification for demonstration purposes.

I saw this post regarding the script unload function but you’d have to code this in before you hit the problem:

Maybe that would help?

1 Like

You don’t actually save the Timer. If you create a global (to that .py file) to hold the timer which is returned by the call to createTimer, you can then call cancel() to cancel the Timer.

mytimer = None

...
    global mytimer
    mytimer = ScriptExecution.createTimer(...

...
    global mytimer
    if mytimer is not None and not mytimer.hasTerminated():
        mytimer.cancel()