import os import datetime import json from django.apps import AppConfig from django.conf import settings from simulation import SimulationThread def simulation(): while True: print("Simulation: {}".format(time.time())) time.sleep(1.0) class TrafficlightfrontendConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'trafficlightfrontend' initialized = False simulation_thread = None # Note as per documentation, may be called more than once # Therefore needs to be idempotent or use flag def ready(self): # Ensure RUN_MAIN to avoid starting thread on runserver "change watchdog" instance if TrafficlightfrontendConfig.initialized or os.environ.get("RUN_MAIN") is None: return print("Traffic Light Frontend: initialization.") print("Current working directory: {}".format(os.getcwd())) periods = json.load(open("periods.json")) SimulationThread.get_instance(periods, start_time=datetime.time.fromisoformat("07:59"), time_factor=4.0).start() TrafficlightfrontendConfig.initialized = True