I don't understand why the function set in apscheduler is unintentionally executed 3 times in Django

Viewed 46

I am creating a web app with Django. I wrote the following codes to add 1 data per minute to the table using APScheduler. When I checked the data generated by APScheduler on the Django admin panel, I found that 3 data were generated per minute for some reason. why does this happen? and how can i solve it?

# models.py
from django.db import models
class Test(models.Model):
    test = models.CharField(max_length=8)
    created_at = models.DateTimeField(auto_now_add=True)
# admin.py
from django.contrib import admin
from .models import Test
class TestAdmin(admin.ModelAdmin):
    list_display = ('test', 'created_at')

admin.site.register(Test, TestAdmin)
# ap_scheduler.py
from apscheduler.schedulers.background import BackgroundScheduler
from .models import Test

def myfunc():
    Test.objects.create(test='test')

def start():
    scheduler = BackgroundScheduler()
    scheduler.add_job(myfunc, 'cron', second=50)
    scheduler.start()
# apps.py
from django.apps import AppConfig
class MembersConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'my_app_name'
    
    def ready(self):
        from .ap_scheduler import start
        start()

バージョン情報

APScheduler==3.9.1
Django==4.0.5
1 Answers

You probably have multiple schedulers due to the auto-reloader is calling the start() command more then once. Try running with:

python manage.py runserver --noreload
Related