Django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet | APScheduler

I have this APScheduler code:

import atexit
from apscheduler.schedulers.background import BackgroundScheduler
from main.utils import run_employee_import

scheduler = BackgroundScheduler()
scheduler.add_job(run_employee_import, "interval", minutes=2)
scheduler.start()

# Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())

When I add this code to settings.py to run it when the app starts to run, it gives me the following error:

raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

PS: I did not include the run_employee_import code because I tested it already (replaced its content with a simple pass) and nothing changed, so it is irrelevant to the error.

I completely changed the way I run the scheduler. And it worked, let me share the solution with you:

I create a .py file inside the app:

app/bulk_task.py

I create a start function and put the schedule code in it:

from apscheduler.schedulers.background import BackgroundScheduler
from main.utils import **<MY_TASK>**
    
def start():
    scheduler = BackgroundScheduler()
    scheduler.add_job(**<MY_TASK>**, "interval", minutes=5)
    scheduler.start()

Then I open the apps.py file of my app, and I add the following code:

from django.apps import AppConfig


class MainConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "main"

    def ready(self):
        from . import bulk_task

        bulk_task.start()

And that's it ;)

Back to Top