Home > Article > Operation and Maintenance > How to implement Django+Nginx+uWSGI scheduled tasks
When Nginx and uWSGI have not been configured, use apscheduler to set up scheduled tasks in url.py alone, and use python manage.py run server, which runs normally; but after the configuration of uWSGI is completed, the entry is from manage.py changes to uwsgi.py, which requires user access to load the apscheduler scheduled task of url.py, and the same scheduled task is started repeatedly with the number of user visits.
Method 1: Migrate the apscheduler scheduled task of url.py to uwgsi.py
Method 2: Use uWSGI's cron
uWSGI's cron official website: 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
Method 1 or 2 requires setting uwsgi.ini worker=1
[uwsgi] # 进程个数 workers=1
Using uWSGI cron is limited to single process. If multiple processes will cause the timer to start repeatedly, you can use socket.bind lock to transform the scheduled task.
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: //定时任务方法
There is a problem. It may be possible to obtain sock.bind(("127.0.0.1", 47200)) at the same time, which can alleviate the duplication problem but cannot be completely solved.
The first step: Create a new Package and write __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
The second step: Set up uwsgi.ini and add mule = package package name/init.py
[uwsgi] mule = package包名/__init__.py
The above is the detailed content of How to implement Django+Nginx+uWSGI scheduled tasks. For more information, please follow other related articles on the PHP Chinese website!