Django_apscheduler calls my job many times

I have a scheduler python package with this main file:

from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events
from django.utils import timezone
from django_apscheduler.models import DjangoJobExecution
import sys

# This is the function you want to schedule - add as many as you want and then register them in the start() function below
def scheduled_function():
    print("my function is running as scheduled")


def start():
    scheduler = BackgroundScheduler()
    scheduler.add_jobstore(DjangoJobStore(), "default")

    scheduler.remove_all_jobs()

    scheduler.add_job(scheduled_function, 'interval', seconds=10, name='scheduled_function', jobstore='default')
    scheduler.start()

    scheduler.print_jobs()

I call it from my apps.py like this:

from django.apps import AppConfig
import os

class MyAppConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'my_server_app'

    def ready(self):
        if os.environ["RUN_MAIN"]: 
            from my_app.scheduler import scheduler
            scheduler.start()

Despite calling remove_all_jobs, my function is called many times. For example, the output of my print_jobs call looks like this after I've restarted django a few times:

Jobstore default:
    scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:43:56 UTC)
    scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:43:56 UTC)
    scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:43:56 UTC)
    scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:44:01 UTC)
    scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:44:02 UTC)
    scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:44:03 UTC)
    scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:44:04 UTC)
    scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:44:05 UTC)
    scheduled_function (trigger: interval[0:00:10], next run at: 2025-01-16 11:44:05 UTC)

How can I fully clear the state of the scheduler whenever start is called?

Вернуться на верх