7 django multithreading python-2.7 background-task
我是Django和django-background-tasks软件包的新手.
我面临一个我无法做的问题/启动后台任务,除非我强行运行命令process_tasks,即python manage.py process_tasks.我想在不运行process_tasks命令的情况下执行/启动后台任务.
settings.py
MAX_ATTEMPTS=1
BACKGROUND_TASK_RUN_ASYNC = True
Run Code Online (Sandbox Code Playgroud)
tasks.py
from background_task import background
#included necessary packages for SMTP
@background(schedule=5)
def test():
#send mail to some ids
Run Code Online (Sandbox Code Playgroud)
views.py
def index(request):
test(schedule=5)
return HttpResponse("Hello, world. ")
Run Code Online (Sandbox Code Playgroud)
忽略我的逻辑.
万一其他人试图让它工作 - 我从我的 Dockerfile 调用一个 shell 脚本,然后运行两个命令。一种用于启动网络服务器(gunicorn 或 run_server),另一种用于运行 manage.py process_tasks 进程。重要的是将 process_tasks 进程作为后台任务运行。
在我的 Dockerfile 的底部有:
CMD ["./run_app.sh"]
我的 run_app.sh 文件如下所示:
#!/usr/bin/env bash
# start background tasks
python manage.py process_tasks &
gunicorn --workers=3 app.wsgi -b 0.0.0.0:8080
Run Code Online (Sandbox Code Playgroud)
请注意流程任务命令中的尾随 &。这使得 shell 脚本能够继续处理并运行 Gunicorn 命令。
希望这对某人有帮助。
这就是 django-background-tasks 的工作原理。您必须运行该进程,任务运行程序才能开始处理任务。
https://github.com/arteria/django-background-tasks#running-tasks