Rule that runs when OH is shutting down

I have a device that I want to turn off when OH is shut down, and turn on when OH is started. There is a rule trigger “System started” which takes care of the latter, but my question is if there is a trigger like “System stopping” that could trigger the former, just before OH starts shutting things down. (ie. when I run systemctl stop openhab.service)

There used to be a System shutdown trigger but it never really worked and was removed a long time ago. I don’t know that there is a way to implement something like that today as a rule trigger and I don’t think, for example, the runlevels back out and count down to 0 ti mirror how they count up during OH start.

However, in text based rules for several languages you have the option to define scriptLoaded and scriptUnloaded function. That’s not quite the same as a system shutdown but it might give you the result you are after. If not, I’m not sure if there is a way to achieve what you are after today.

I am using DSL rules, so unfortunately cannot use that.

Perhaps I should have another try to re- add that back into the core?

Or perhaps I should think about creating a rudimentary binding with one thing / channel that goes on when initialize() is called, and off when dispose() is called? I guess the issue would be whether, on shutdown, the core kills the rules engine before it kills the bindings and things, or vice versa…

There is an open PR to add the scriptLoaded and scriptUnloaded to Rules DSL I believe.

It was taken out because it never worked and at the time they couldn’t figure out. a way to make it work. It’s also a little tricky because if OH is closing down, it’s shutting down everything in parallel. There is no guarantee that even is your rule manages to run before the rule engine closes down, the Thing will very likely have already closed down.

Yeah… but I think it is not quite “in parallel” … I may play around a bit and see…

Got it here – thank you. I will import that into my operative system and see if it works.

Are you typing in the command systemctl stop openhab.service ?

You could create a script to turn it off then run command.

You could edit the service to turn it off before openhab starts to stop.

Isn’t it independent of typing systemctl stop openhab.service ? As long as the service or the host is being shutdown my understanding/knowledge is that it will go via the service setup. Which means the service file is being used. So dependencies in services could be used to have influence on the sequence of to be shutdown services ( as you suggested ).