Apscheduler调用函数太快

2024-05-15 09:05:14 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的scheduler.py文件:

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 hello():
    print("Hello")


def start():
    scheduler = BackgroundScheduler()
    scheduler.add_jobstore(DjangoJobStore(), "default")
    # run this job every 10 seconds
    scheduler.add_job(hello, 'interval', seconds=10, jobstore='default')
    register_events(scheduler)
    scheduler.start()
    print("Scheduler started...", file=sys.stdout)

我的Django应用程序在本地主机上运行良好。我只是尝试在终端上每隔10秒打印一次“hello”,但有时一次打印3或4个。为什么会这样?这只是帮助理解ApsScheduler的基础模板


Tags: thedjangofromimportregisteraddhellosys
1条回答
网友
1楼 · 发布于 2024-05-15 09:05:14

发生这种情况的主要原因是,如果您在运行开发服务器时没有设置 noreload标志,这将导致调度程序被调用两次(有时甚至更多)

在开发中运行服务器时,请按以下方式进行尝试:

python manage.py runserver localhost:8000  noreload

看看会发生什么。如果仍然发生这种情况,可能是时间间隔太近,因此当系统开始使用它时,仍在调用另一个版本(即使它是一个非常短的函数)。Django将所有挂起、过期和运行的作业存储在数据库中,因此它必须在每个事务之后存储作业的记录。试着扩大间隔,看看会发生什么

如果这些都不起作用,请发布你正在使用的代码的其余部分,我将用其他选项更新我的答案。我在过去也遇到过类似的问题,但是通过设置 noreload选项就解决了。当您在生产环境中使用DEBUG=False在常规web服务器后面运行它时,它也应该自行解析

相关问题 更多 >