Adding listeners to Ignition

Something I have been thinking about since you wrote this, how would one do this? I didnt realize this was possible with the way Ignition orchestrates the jython unless I am overcomplicating how I would think this worked. Do you have a link to a forum example of this?

There’s a lot of places you could theoretically add a listener to Ignition code. A very common pattern in Ignition (and Java overall, for that matter) is for there to be some central ‘manager’ for a subsystem, and for it to manage a list of ‘listener’ classes. The manager will automatically invoke the appropriate method on every listener it has ‘registered’ when the matching event fires.

So, you could get an instance of the ProjectManager from the gateway context, then add a ProjectListener. You call addProjectListener with your own instance of the ProjectListener interface (in Java, it’s very easy to make anonymous classes; it’s somewhat more awkward from Python/Jython).
Then you just do whatever action you need to in the methods defined by the interface; e.g. if you need to trigger some cleanup when a project is deleted, you could do that accordingly.

The complication when doing things like this from scripting, rather than through a module, is that Jython’s compilation process is complicated. There’s lots of references and caching and various other layers involved. It’s very easy to add a listener to some persistent object on the gateway - but if you don’t take steps, when you next make an update to your script library, the entire Jython interpreter will be removed and recreated. Normally that can happen and be cleaned up by the garbage collector - but your custom listener class can have a backreference to the the entire Jython instance - meaning a large chunk of memory is unable to be released.

That is why adding listeners is very fraught and Phil cautions against it so much.

1 Like