#1
16th May 2022 at 11:17 AM
Posts: 127
Thanks: 2224 in 17 Posts
10 Achievements
Best practice to inject code that needs services to be initialized
Hi modders!
I'm wondering: what's the best practice inject code if one has to be sure that services have already been initialized?
My usecase: I want to set up an alarm and for this purpose I also need the TimeService.
The only way that worked for me so far is a solution based on this
tutorial :
Code:
def run_once(function):
def wrapper(*args, **kwargs):
if not wrapper.has_run:
wrapper.has_run = True
return function(*args, **kwargs)
wrapper.has_run = False
return wrapper
@run_once
def setup_alarm():
now = services.time_service().sim_now
# setup alarm stuff
sims4.callback_utils.add_callbacks(sims4.callback_utils.CallbackEvent.PROCESS_EVENTS_FOR_HOUSEHOLD_ENTER, setup_alarm)
What I like about this solution is that it's cleaner in the sense of that it uses a native method for injecting code without me having to inject it manually into some function. And that it works, because setup_alarm only gets called when the services have actually been initialized.
What I don't like is that it somehow get's executed a bunch of times, therefore the run_once hack...
Is there a better/cleaner way to achieve this?