标签:www. tom cron broker tab ber eid cal 功能
celery支持定时任务,设定好任务的执行时间,celery就会定时自动帮你执行, 这个定时任务模块叫celery beat
项目前提: 安装并启动Redis
celery_Schedule.py
# version: python3.2.5 # author: ‘lft415659‘ from celery import Celery from celery.schedules import crontab # 可以实现复杂的定时任务 app = Celery(‘CelerySchedule‘, # redis://:password@hostname:port/db_number 有密码认证的连接 broker=‘redis://192.168.2.105‘, # broker=‘redis://:密码@192.168.2.105:6379/0‘, backend=‘redis://192.168.2.105‘, # 用于Celery的返回结果的接收 ) # 创建定时任务 @app.on_after_configure.connect # 启动程序连接上celery后自动执行这个函数生成定时任务 def setup_periodic_tasks(sender, **kwargs): # 第一次参数必须是sender,是定时任务的一个实例 # Calls test(‘hello‘) every 10 seconds. 这里的test是我们自定义的函数 sender.add_periodic_task(10.0, test.s(‘hello‘), name=‘add every 10‘) # Calls test(‘world‘) every 30 seconds sender.add_periodic_task(30.0, test.s(‘world‘), expires=10) # Executes every Monday morning at 7:30 a.m. 更复杂的定时任务 sender.add_periodic_task( crontab(hour=7, minute=30, day_of_week=1), test.s(‘Happy Mondays!‘), ) @app.task def test(arg): print(‘run task:‘, arg)
后台启动Celery的worker任务:
omc@omc-virtual-machine:~$ cd Celery omc@omc-virtual-machine:~/Celery$ vim celery_Schedule.py omc@omc-virtual-machine:~/Celery$ celery -A celery_Schedule worker -l info
启动定时任务调度器[celery beat]
omc@omc-virtual-machine:~/Celery$ celery -A celery_Schedule beat
上面的定时任务比较简单,只是每多少s执行一个任务,但如果你想要每周一三五的早上8点给你发邮件怎么办呢?哈,其实也简单,用crontab功能,跟linux自带的crontab功能是一样的,可以个性化定制任务执行时间
【linux crontab】http://www.cnblogs.com/peida/archive/2013/01/08/2850483.html
【更多参考】http://www.cnblogs.com/alex3714/articles/6351797.html
from celery.schedules import crontab app.conf.beat_schedule = { # Executes every Monday morning at 7:30 a.m. ‘add-every-monday-morning‘: { ‘task‘: ‘tasks.add‘, ‘schedule‘: crontab(hour=7, minute=30, day_of_week=1), ‘args‘: (16, 16), }, }
app.conf.beat_schedule = { ‘add-every-30-seconds‘: { ‘task‘: ‘tasks.add‘, ‘schedule‘: 30.0, ‘args‘: (16, 16) }, } app.conf.timezone = ‘UTC‘
标签:www. tom cron broker tab ber eid cal 功能
原文地址:https://www.cnblogs.com/ftl1012/p/9457698.html