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-12,0分点执行一次
crontab(month_of_year=”*/3”) 每3个月执行一次
crontab(minute=0,hour=0,day_of_month=”2-31/2”) 偶数天的0时0分执行
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)
使用钉钉自定义机器人,实现定时任务