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

1、安装

pip install django-background-tasks

2、注册服务

INSTALLED_APPS = [
    ...
    'background_task',
]

3、生成表 

 

// 生成迁移
python manage.py makemigrations
//运行迁移
python manage.py migrate

4、创建文件,模拟任务

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、调用

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 manage.py process_tasks

7、访问方法,开始执行 

你可能感兴趣的:(Django,python,django,python,后端)