场景说明:
Django项目需要实现每30秒刷新一次首页信息
1.安装库
pip install django-q
2.添加app
INSTALLED_APPS = [# ... 其他应用程序 ...'django_q',]
3.配置
Q_CLUSTER={ 'name':'project', 'workers':4, 'recycle':500, 'timeout':60, 'compress':True, 'cpu_affinity':1, 'save_limit':250, 'queue_limit':500, 'label':'DjangoQ', 'redis':{ 'host':'127.0.0.1', 'port':6379, 'db':0, } }
4.定义一个任务,例如打印一条消息(异步执行)
# tasks.py
from django_q.tasks import async_task
def print_message():print("This is a message from Django - Q")
async_task(print_message)
5.定时任务示例
from django_q.models import Schedule
from django_q.tasks import async_task
import timedef my_task():print("This task is executed every 30 seconds.")# 这里可以添加实际要执行的任务逻辑,比如更新数据、发送通知等# 创建定时任务
Schedule.objects.create(func='your_app_name.q_tasks.my_task', # 替换为你的应用名称和任务函数所在的模块路径schedule_type=Schedule.MINUTES,minutes=0.5, # 因为0.5分钟就是30秒repeats=-1 # -1表示无限重复执行任务
)
6.启动Django-Q
import qcluster
qcluster.start()
7.启动项目,启动后队列也开始执行