Django+Nginx+uWSGI定时任务怎么实现

摘要

在Nginx和uWSGI还没配置时,单独在url.py使用apscheduler设置定时任务,使用python manage.py run server,运行正常;但是在配置完成uWSGI后,入口从manage.py变为uwsgi.py,导致需要用户访问后才能加载url.py的apscheduler定时任务,并且随用户访问次数,同一定时任务重复启动。

使用uWSGI的cron

方法一:将url.py的apscheduler定时任务迁移到uwgsi.py

方法二:使用 uWSGI的cron

uWSGI的cron官网 : https://uwsgi-docs-zh.readthedocs.io/zh_CN/latest/Cron.html

end=1 while end: try: import uwsgi //建立job_id为0,每天12:12启动fuc的定时器,-1代表*(全部) uwsgi.register_signal(0, "", fuc) uwsgi.add_cron(0, 12,12,-1,-1,-1) end=0 except: pass

方法一或方法二都需要设置uwsgi.ini的worker=1

[uwsgi] # 进程个数 workers=1

使用socket.bind锁

使用uWSGI的cron只限于单进程情况下使用,如果多进程会导致定时器重复启动问题,可以使用socket.bind锁改造定时任务。

try: import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("127.0.0.1", 47200)) except socket.error: logger.info('禁止成功') else: //定时任务方法

存在问题,可能存在同时获取 sock.bind((“127.0.0.1”, 47200)),能够减缓重复问题,不能完全解决。

使用uWSGI的mule

第一步:新建一个Package,编写__init__.py

//如果是Django项目,需要加上才可以使用django的model //import django //os.environ.setdefault('DJANGO_SETTINGS_MODULE', '项目名.settings') //django.setup() from apscheduler.schedulers.background import BackgroundScheduler scheduler = BackgroundScheduler() //scheduler.add_job不详说,具体看官网文档 scheduler.add_job(...,timezone='Asia/Shanghai') scheduler.start() try: import uwsgi while True: sig = uwsgi.signal_wait() except Exception as err: pass

第二步:设置uwsgi.ini,增加mule = package包名/init.py

[uwsgi] mule = package包名/__init__.py

以上就是Django+Nginx+uWSGI定时任务怎么实现的详细内容,更多请关注主机测评网其它相关文章!

阅读剩余
THE END