The issue I suspect your having is how to trigger the startup of that in Django. You have multiple options, mostly consisting of “putting it somewhere it will be run”. For example, add it to the bottom of a models.py file, or in urls.py and it will be processed once on each Django restart, then continue to run in the background. Database accesses can then be performed as normal from within the function - just import your models as normal for your queries.
import time
from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import register_events, register_job
from django_apscheduler.jobstores import DjangoJobStore
scheduler = BackgroundScheduler()
# If you want all scheduled jobs to use this store by default,
# use the name 'default' instead of 'djangojobstore'.
scheduler.add_jobstore(DjangoJobStore(), 'default')
# If you want per-execution monitoring, call register_events on your scheduler:
register_events(scheduler)
@register_job(scheduler, "interval", seconds=1)
def test_job():
time.sleep(4)
print("I'm a test job!")
# raise ValueError("Olala!")
scheduler.start()
print("Scheduler started!")