首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用apache & mod wsgi配置django ap调度程序

使用apache & mod wsgi配置django ap调度程序
EN

Stack Overflow用户
提问于 2021-02-01 08:39:36
回答 1查看 839关注 0票数 1

我已经通过运行以下命令- python manage.py runap调度器在django项目中配置了django ap调度程序

但是现在我们已经将应用程序移到生产服务器上,并配置了Apache & Mod wsgi,所以现在如何配置和运行ap调度器。

请给我建议。

EN

回答 1

Stack Overflow用户

发布于 2021-04-19 10:53:47

https://medium.com/@mrgrantanderson/replacing-cron-and-running-background-tasks-in-django-using-apscheduler-and-django-apscheduler-d562646c062e解释了如何设置包含调度程序的AppConfig:

为此,您必须在settings.py中添加以下内容

代码语言:javascript
复制
INSTALLED_APPS = [
    ...
    "django_apscheduler",
]

# This scheduler config will:
# - Store jobs in the project database
# - Execute jobs in threads inside the application process
SCHEDULER_CONFIG = {
    "apscheduler.jobstores.default": {
        "class": "django_apscheduler.jobstores:DjangoJobStore"
    },
    'apscheduler.executors.processpool': {
        "type": "threadpool"
    },
}
SCHEDULER_AUTOSTART = True

启动调度程序的文件可能如下所示:

代码语言:javascript
复制
import logging

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ProcessPoolExecutor, ThreadPoolExecutor
from django_apscheduler.jobstores import register_events, register_job

from django.conf import settings

# Create scheduler to run in a thread inside the application process
scheduler = BackgroundScheduler(settings.SCHEDULER_CONFIG)

def start():
    if settings.DEBUG:
        # Hook into the apscheduler logger
        logging.basicConfig()
        logging.getLogger('apscheduler').setLevel(logging.DEBUG)

    # Adding this job here instead of to crons.
    # This will do the following:
    # - Add a scheduled job to the job store on application initialization
    # - The job will execute a model class method at midnight each day
    # - replace_existing in combination with the unique ID prevents duplicate copies of the job
    scheduler.add_job("core.models.MyModel.my_class_method", "cron", id="my_class_method", hour=0, replace_existing=True)

    # Add the scheduled jobs to the Django admin interface
    register_events(scheduler)

    scheduler.start()

启动调度程序的AppConfig如下所示:

代码语言:javascript
复制
from django.conf import settings

class CoreConfig(AppConfig):
    name = "core"

     def ready(self):
        from . import scheduler
        if settings.SCHEDULER_AUTOSTART:
            scheduler.start()

(从上面链接的教程复制的所有代码)。

但是请注意,django-ap调度程序在他们的自述文件中声明

这种简单性的折衷之处在于,您需要小心确保只有一个调度程序在特定时间点积极运行。(https://github.com/jcass77/django-apscheduler#quick-start)。

如果您在多线程Django-Environment中高效地运行调度程序,据我所知,这并不能得到保证。因此,这个解决方案肯定应该是一丁点儿的--更合适的方法是遵循自述文件的建议,为调度程序发出阻塞命令,并独立于您在一个专用进程中所提供的服务来运行该命令。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65989475

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档