nginx uwsgi 启动 django APScheduler 问题

        最近项目需要一个定时任务,本来打算不写进Django 的,因为只是一个简单的定时任务。因此就直接加入到了 Django,

本地使用Django 为1.9.2 版本, 

APScheduler3.6.1 

APScheduler的使用这里不做过多说明,网上搜索会有很多例子。

写完之后测试没有问题,就直接在服务器上运行,重启服务后,一直 没有运行,奇怪是什么原因呢,怎么就不允许了呢。

python manage.py runserver 192.168.1.130:9000 运行 ,发现任务又运行了,uwsgi启动,等了会又不运行。

     因为我是将定时任务写进了view 文件,整个scheduler  初始化都是通过调用view 文件进行的, 但是

使用python manage.py runserver 0.0.0.0:80启动项目是通过manage.py进行驱动的,无论调用放 置在哪个视图文件中,都会被调用,而使用uwsgi进行驱动后,不调用manage.py,导致无法启动计划任务。

解决办法:

1.uwsgi配置添加--enable-threads = true  允许在django 内部启动子线程

2.在项目的wsgi.py文件导入APScheduler实例化对象

import os

from django.core.wsgi import get_wsgi_application
from BusinessLogic.viewResources import scheduler 

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testAPP.settings")

application = get_wsgi_application()

      然后重启发现允许了, 但是伴随着也有了新等待问题出现, uwsgi 的配置是4个worker  ,然后4个Worker 都运行了整个定时任务。不断的重复运行, 而且执行都失败了。

        发生这个问题的原因在于uwsgi启动了多个进程来提供服务,于是每次启动的时候定时任务都会跟着再启动一次,于是有4个进程的话,对应的服务就会启动4次,除了第一次可能执行成功后面的基本都会挂掉。这样一想肯定是多个进程造成的,

要解决这个问题其实也不难,只要保证在第一次启动的时候添加定时任务并且执行,以后启动的进程不再处理定时任务即可

方法1:

import sys, socket
 
try:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(("127.0.0.1", 47200))
except socket.error:
    print "!!!scheduler already started, DO NOTHING"
else:
    from apscheduler.schedulers.background import BackgroundScheduler
    scheduler = BackgroundScheduler()
    scheduler.start()
    print "scheduler started"

方法2:

import atexit
import fcntl
from flask_apscheduler import APScheduler
 
def init(app):
    f = open("scheduler.lock", "wb")
    try:
        fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
        scheduler = APScheduler()
        scheduler.init_app(app)
        scheduler.start()
    except:
        pass
    def unlock():
        fcntl.flock(f, fcntl.LOCK_UN)
        f.close()
    atexit.register(unlock)

 

你可能感兴趣的:(python)