Django celery定时任务

celery 定时任务

电商项目有这样的需求,每天中午12点进行秒杀活动,对于有过预约的用户,
在11:50进行短信提醒。最初接触定时任务是在Linux系统的计划任务部分。
Celery已经提供了这样的一种功能。

Django celery常用的定时方法
crontab

crontab(hour=*/2)2小时执行一次
crontab(minute=0,hour=*/3)3个小时的0分执行一次
crontab(minute=0,hour=*/3,8-12)3小时或者8-120分点执行一次
crontab(month_of_year=*/3)3个月执行一次
crontab(minute=0,hour=0,day_of_month=2-31/2) 偶数天的00分执行
crontab(0,0,day_of_month=1,month_of_year=5) 每年五月一号执行

timedelta

timedelta(seconds=1) 每秒执行一次

开启celery定时任务步骤:
1、启动Django项目
2、开启redis数据库
3、启动celery worker服务

python manage.py celery worker -l info

4、启动celery定时任务

python manage.py celerybeat -l info

setting配置

# celery 的定时器
from celery.schedules import crontab
from celery.schedules import timedelta

CELERYBEAT_SCHEDULE = {  # 定时器策略
    # 定时任务一:每隔30s运行一次
    u'测试定时器1': {
        'task': 'CeleryTask.tasks.taskExample',
        # 'schedule': crontab(minute='*/2'),
        'schedule': timedelta(seconds=30),
        'args': (),
    },
    u'熊大的叫床服务': {
        'task': 'CeleryTask.tasks.DingTalk',
        # 'schedule': crontab(minute='*/2'),
        'schedule': timedelta(seconds=3),
        'args': (),
    },
}


在tasks.py文件中定义相应的逻辑处理函数,并将其转换为一个个的任务

from __future__ import absolute_import
import requests
import json
from DjangoShop.celery import app  # 在安装celery框架成功后,django新生成的模块

@app.task # 将taskExample转换为一个任务
def taskExample():
    print("send email ok!")

@app.task
def add(x=1,y=2):
    return x+y

@app.task
def DingTalk():
    url = "https://oapi.dingtalk.com/robot/send?access_token=3854f74dd13b9cc7ae451c13efdbd0dff0749bf822d792f53b0088f44ad7b37c"

    headers = {
        "Content-Type": "application/json",
        "Chartset": "utf-8"
    }

    requests_data = {
        "msgtype": "text",
        "text": {
            "content": "睡醒了吧,熊大。你亲爱的Mom正在路上了,快点起来了!"
        },
        "at": {
            "atMobiles": [
            ],
            "isAtAll": True
        }
    }

    sendData = json.dumps(requests_data)

    response = requests.post(url, headers=headers, data=sendData)

    content = response.json()

    print(content)

使用钉钉自定义机器人,实现定时任务
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值