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、访问方法,开始执行

相关推荐
文人sec41 分钟前
pytest1-接口自动化测试场景
软件测试·python·单元测试·pytest
WX-bisheyuange2 小时前
基于Spring Boot的民宿预定系统的设计与实现
java·spring boot·后端·毕业设计
卷福同学2 小时前
【AI编程】用Codebuddy+lighthouse开发AI年龄模拟网站
javascript·后端
secondyoung2 小时前
Mermaid流程图高效转换为图片方案
c语言·人工智能·windows·vscode·python·docker·流程图
5***79003 小时前
后端API设计趋势,GraphQL与REST对比
后端·graphql
nini_boom3 小时前
**论文初稿撰写工具2025推荐,高效写作与智能辅助全解析*
大数据·python·信息可视化
桜吹雪3 小时前
手搓一个简易Agent
前端·人工智能·后端
William_cl3 小时前
【ASP.NET进阶】Controller层核心:Action方法全解析,从基础到避坑
后端·asp.net
1***s6323 小时前
Python爬虫反爬策略,User-Agent与代理IP
开发语言·爬虫·python