创建一个名叫tasks.py的文件,里边单独存放定时任务函数
from datetime import timedelta
from django.utils import timezone
from polls.models import User
from vote import app
@app.task
def check_inactive_user():
"""检查不活跃用户"""
time_before_30days = timezone.now() - timedelta(days=30)
User.objects.filter(last_visit__lte=time_before_30days).\
filter(is_active=True).update(is_active=False)
@app.task
def update_user_votecount():
"""更新用户票数为5票"""
User.objects.filter(is_active=True).update(vote_count=5)
写好定时任务函数后,在__init__.py文件中,配置定时任务的执行计划
import celery
from celery.schedules import crontab
from vote import settings
# 自动从指定的位置发现被@app.task装饰过的任务
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
# 通过Celery对象的conf属性的update消息配置定时任务
app.conf.update(
timezone=settings.TIME_ZONE,
enable_utc=True,
# 定时任务(计划任务)相当于是消息的生产者
# 如果只有生产者没有消费者那么消息就会在消息队列中积压
# 将来实际部署项目的时候生产者、消费者、消息队列可能都是不同节点
beat_schedule={
'check_inactive_user': {
'task': 'polls.tasks.check_inactive_user',
'schedule': crontab(minute=30, hour=23),
},
'update_user_votecount': {
'task': 'polls.tasks.update_user_votecount',
'schedule': crontab(minute=0, hour=0),
},
},
)
terminal 1 --生成消息队列
celery -A vote beat -l debug
terminal 2 --执行消息队列
celery -A vote worker -l debug
本文介绍了一个使用Celery实现的定时任务管理系统,包括两个主要任务:检查并处理长时间未活跃的用户及每天更新用户的投票计数。
958

被折叠的 条评论
为什么被折叠?



