安装django-background-tasks
pip3 install django-background-tasks
在settings.py中编辑如下
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'background_task', # 添加这行
...
]
在需要用到后台任务的方法上添加装饰器
from background_task import background
@background(schedule=1)
def run_task():
...
创建对应的数据库
python3 manage.py makemigrations background_task
python3 manage.py migrate
另开终端启动background-task
python3 manage.py process_tasks