安装django-background-tasks

  1. pip3 install django-background-tasks

在settings.py中编辑如下

  1. INSTALLED_APPS = [
  2. 'django.contrib.admin',
  3. 'django.contrib.auth',
  4. 'django.contrib.contenttypes',
  5. 'django.contrib.sessions',
  6. 'django.contrib.messages',
  7. 'django.contrib.staticfiles',
  8. 'background_task', # 添加这行
  9. ...
  10. ]

在需要用到后台任务的方法上添加装饰器

  1. from background_task import background
  2. @background(schedule=1)
  3. def run_task():
  4. ...

创建对应的数据库

  1. python3 manage.py makemigrations background_task
  2. python3 manage.py migrate

另开终端启动background-task

  1. python3 manage.py process_tasks