Django异步执行任务django-background-tasks

1、安装

pip install django-background-tasks

2、注册服务

python 复制代码
INSTALLED_APPS = [
    ...
    'background_task',
]

3、生成表

python 复制代码
// 生成迁移
python manage.py makemigrations
//运行迁移
python manage.py migrate

4、创建文件,模拟任务

python 复制代码
from background_task import background # type: ignore
import time

@background(schedule=10)  # 任务将在 10 秒后执行
def send_email_task(subject, message):
    print(f"Sending email: {subject}, {message}")
    time.sleep(20)  # 模拟耗时操作
    print("Email sent successfully!")

5、调用

python 复制代码
def tasks_list(request):
    #测试执行任务
    for i in range(3):
        print(i)
        send_email_task('Hello', 'This is a test email')
        #time.sleep(1)
        # 返回字符串
    return HttpResponse('Not Found')  # 正确:返回一个 HttpResponse 对象    

6、启动后台进程

python 复制代码
python manage.py process_tasks

7、访问方法,开始执行

相关推荐
云程笔记1 小时前
004.环境搭建基础篇:Python、CUDA、cuDNN、PyTorch/TensorFlow安装与版本兼容性踩坑
pytorch·python·tensorflow
知行合一。。。6 小时前
Python--04--数据容器(总结)
开发语言·python
架构师老Y6 小时前
008、容器化部署:Docker与Python应用打包
python·容器·架构
lifewange7 小时前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
GreenTea7 小时前
一文搞懂Harness Engineering与Meta-Harness
前端·人工智能·后端
pluvium277 小时前
记对 xonsh shell 的使用, 脚本编写, 迁移及调优
linux·python·shell·xonsh
2401_827499997 小时前
python项目实战09-AI智能伴侣(ai_partner_5-6)
开发语言·python
PD我是你的真爱粉7 小时前
MCP 协议详解:从架构、工作流到 Python 技术栈落地
开发语言·python·架构
ZhengEnCi8 小时前
P2G-Python字符串方法完全指南-split、join、strip、replace的Python编程利器
python
是小蟹呀^8 小时前
【总结】LangChain中工具的使用
python·langchain·agent·tool