使用celery执行异步定时任务

创建一个名叫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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值