Jython Timer not working after update to 3.2

Dear Openhabians,

I was running OH3.2 M3 without problems and updated to the OH3.2 stable. My previously running rules in jython now stopped working when they try to invoke a timer. Here is a sample timer:

from core.rules import rule
from core.triggers import when
from threading import Timer

.... 


if timerBR is None or str(timerBR.getState()) == "TERMINATED":
        timerBR = Timer(600, lambda: events.sendCommand("DachlukeBad_Position","0"))
        timerBR.start()
        BR_Hatch_Timer.log.info("FF Hatch timer started.")
        events.sendCommand("H_Auto_Window_Active","ON")
2021-12-23 09:55:29.047 [WARN ] [jsr223.jython                       ] - Traceback (most recent call last):
  File "/etc/openhab/automation/lib/python/core/log.py", line 65, in wrapper
    return function(*args, **kwargs)
  File "/etc/openhab/automation/lib/python/core/rules.py", line 109, in execute
    self.callback(inputs.get('event'))
  File "/etc/openhab/automation/jsr223/python/personal/windows.py", line 61, in BR_Hatch_Timer
    timerBR = Timer(600, lambda: events.sendCommand("DachlukeBad_Position","0"))
  File "/var/lib/openhab/cache/org.eclipse.osgi/263/0/bundleFile/Lib/threading.py", line 330, in Timer
    return _Timer(*args, **kwargs)
  File "/var/lib/openhab/cache/org.eclipse.osgi/263/0/bundleFile/Lib/threading.py", line 341, in __init__
    Thread.__init__(self)
  File "/var/lib/openhab/cache/org.eclipse.osgi/263/0/bundleFile/Lib/threading.py", line 196, in __init__
    _thread = self._create_thread()
  File "/var/lib/openhab/cache/org.eclipse.osgi/263/0/bundleFile/Lib/threading.py", line 209, in _create_thread
    return _newFunctionThread(self.__bootstrap, ())
IllegalThreadStateException: java.lang.IllegalThreadStateException

Does anybody have this problem, too? I am using a little older version of the jython helper libraries, which might be the culprit. But I don’t want to just update them while all other rules are working fine (those without timer) and mess it all up before Christmas day (family will make fun of me…).

Thanks and all the best,

Bob

i just copied your code and for me it seems to work, of course i had to edit a little, and i added the variable outside the rule and defined it as global inside the rule (timer starts when rule is loaded and again always when item ivi receives a command):

from core.rules import rule
from core.triggers import when
from threading import Timer


timerBR = None


@rule("Jython test (1_test.py)",\
    description="Für Versuche und Tests",\
    tags=["Jython", "beispiele"])   # description and tags are optional
@when("System started")
@when("Item ivi received command")
def jythonTest(event):
    global timerBR
    LogAction.logInfo(u"jythonTest", u"### start jythonTest funktion ##############")

    if timerBR is None or str(timerBR.getState()) == "TERMINATED":
            timerBR = Timer(6, lambda: events.sendCommand("iBuero_Li","0"))
            timerBR.start()
            LogAction.logInfo(u"jythonTest", u"### FF Hatch timer started.")
            events.sendCommand("iBuero_Li","60")

    LogAction.logInfo(u"jythonTest", u"### ENDE jythonTest funktion ##############")

to be honest i dont know which helper libraries i use, i think i installed ivans helper libraries.

i am working with oh 3.2.0 release build

Thank you so much Stefan,

I will try to update to ivans helper libraries then! I am still on 5ivers with the fix for OH3.

I’ll report back if that solved my problem!

Edit:
Installing ivans helper libraries did the trick! Thanks again for the help!!

Sorry to open this up again.

Appearently it works for a certain time after I restart openhab, and then stops working…
Almost like the threads stick around and then it can’t create new ones anymore.

Is there a way to debug this further?
How do I find the timer threads in the karaf console?

Again, thank you so much!

i dont work with the threading timer. i use scriptexecution timers, many of them and without issues. do you know them? they even can easily be rescheduled:

from time import sleep
from core.rules import rule
from core.triggers import when
from core.actions import LogAction, ScriptExecution
from java.time import ZonedDateTime



init_delay_timer = None

def jythonTest_body():
    global init_delay_timer

    if isinstance(items["iEWoK_Abzug_Li_Kt"], UnDefType):
        LogAction.logInfo(u"jythonTest_body", "Items noch uninitilaisiert, warten")
        init_delay_timer.reschedule(ZonedDateTime.now().plusMinutes(1))
        return

    init_delay_timer.cancel()
    init_delay_timer = None
    LogAction.logInfo(u"jythonTest_body", "Systemstart, Abzug initialisieren")

    # ... do sth

  

@rule("Jython test (1_test.py)",\
    description="Für Versuche und Tests",\
    tags=["Jython", "beispiele"])   # description and tags are optional
@when("System started")
@when("Item ivi received command")
def jythonTest(event):
    LogAction.logError(u"jythonTest", u"### ööääüü start jythonTest funktion ##############")

    global init_delay_timer
    init_delay_timer = ScriptExecution.createTimer(ZonedDateTime.now().plusMinutes(2), jythonTest_body)

    LogAction.logInfo(u"jythonTest", u"### ENDE jythonTest funktion ##############")





1 Like

Thanks i am trying this now. But when I try to load my new scipts i get:

2021-12-24 09:50:00.527 [INFO ] [rulesupport.loader.ScriptFileWatcher] - Loading script '/etc/openhab/automation/jsr223/python/personal/nuki.py'
2021-12-24 09:50:00.554 [ERROR] [ipt.internal.ScriptEngineManagerImpl] - ScriptEngine for language 'py' could not be created for identifier: file:/etc/openhab/automation/jsr223/python/personal/nuki.py
2021-12-24 09:50:00.556 [ERROR] [rulesupport.loader.ScriptFileWatcher] - Script loading error, ignoring file: /etc/openhab/automation/jsr223/python/personal/nuki.py

I guess something with the old timer method I used is blocking all threads and then jython stops working… Very weird that this used to work with the last milestones and now stopped working.

Anyways im rebooting openhab and i guess then it’ll load my changes!

puh sorry, dont know. is nuky.py your only python file or is the error appearing at all py-files? perhaps try to create a new file and then insert there some simple code to see if that works.

It happens with all the py files. I have integrated your suggestion now and up to now it’s working fine :slight_smile:
I hope it’ll stay that way! Thank you so much for your help and a merry christmas to you!

All the best,

Bob

I migrated from OH3.1 to OH3.2 yesterday and experience the same issue with the threading timer.

2022-01-10 08:51:29.753 [WARN ] [jsr223                              ] - Traceback (most recent call last):
  File "C:\Bin\openHAB\current\conf\automation\lib\python\core\log.py", line 96, in wrapper
    return function(*args, **kwargs)
  File "C:\Bin\openHAB\current\conf\automation\lib\python\core\rules.py", line 108, in execute
    self.callback(inputs.get('event'))
  File "/C:/Bin/openHAB/current/conf/automation/jsr223/python/personal/ecl.py", line 232, in ecl_scene_cuisine
  File "C:\Bin\openHAB\current\conf\automation\lib\python\personal\run.py", line 34, in schedule
    cur_func = Run(target, args, func_name, logger)
  File "C:\Bin\openHAB\current\conf\automation\lib\python\personal\run.py", line 40, in __init__
    Thread.__init__(self)
  File "C:\Bin\openHAB\current\userdata\cache\org.eclipse.osgi\259\0\bundleFile\Lib\threading.py", line 196, in __init__
    _thread = self._create_thread()
  File "C:\Bin\openHAB\current\userdata\cache\org.eclipse.osgi\259\0\bundleFile\Lib\threading.py", line 209, in _create_thread
    return _newFunctionThread(self.__bootstrap, ())
IllegalThreadStateException: java.lang.IllegalThreadStateException

All my scripts use a custom Jython lib with a Run class that allows starting/repeating/stopping functions:

Run.schedule(myfunction, 
[func_params]).delaystart(a_delay).repeat(delay_between_repeats).stopAfter(delay_for_stop)
and
Run["myfunction"].stop()

So, returning to OH3.1 until that new regression is fixed (as usual when a new version is released…)