运行 在指定时间在 Django Celery 中执行任务?
Running tasks in Django Celery at specified time?
我的 tasks.py 文件的片段如下:
from celery.task.schedules import crontab
from celery.decorators import periodic_task
@periodic_task(
run_every=crontab(minute='15, 45', hour='0, 7, 15'),
)
def task1():
send_mail()
我希望 task1() 中的脚本仅在 00:15、7:15 触发 和 15:45,而根据当前设置,它在 00:15、00:45 触发、7:15、7:45、15:15 和 15:45.
我该怎么做?另外,如果有更好的方法,请告诉我!
你有两个选择。一是定义几次装饰函数:
def _task1():
send_mail()
task1_a = @periodic_task(
_task1,
run_every=crontab(minute='15', hour='0, 7'),
)
task1_b = @periodic_task(
_task1,
run_every=crontab(minute='45', hour='15'),
)
另一种选择是定义自定义计划实施 celery's schedule interface。
看完documentation, and borrowing some ideas from 后,我着手解决这个问题如下:
删除 periodic_task 装饰器并更新 tasks.py
如:
from celery.task.schedules import crontab
from celery.decorators import periodic_task
@task
def task1():
send_mail()
在celery.py中添加beat schedule为:
app.conf.beat_schedule = {
'alert': {
'task': 'app.tasks.task1',
'schedule': crontab(minute='15', hour='0, 7')
},
'custom_alert': {
'task': 'app.tasks.task1',
'schedule': crontab(minute='45', hour='15')
}
}
使用这些设置,task1() 中的 script 仅在所需时间触发(0:15,7:15 和 15:45)!
我的 tasks.py 文件的片段如下:
from celery.task.schedules import crontab
from celery.decorators import periodic_task
@periodic_task(
run_every=crontab(minute='15, 45', hour='0, 7, 15'),
)
def task1():
send_mail()
我希望 task1() 中的脚本仅在 00:15、7:15 触发 和 15:45,而根据当前设置,它在 00:15、00:45 触发、7:15、7:45、15:15 和 15:45.
我该怎么做?另外,如果有更好的方法,请告诉我!
你有两个选择。一是定义几次装饰函数:
def _task1():
send_mail()
task1_a = @periodic_task(
_task1,
run_every=crontab(minute='15', hour='0, 7'),
)
task1_b = @periodic_task(
_task1,
run_every=crontab(minute='45', hour='15'),
)
另一种选择是定义自定义计划实施 celery's schedule interface。
看完documentation, and borrowing some ideas from
删除 periodic_task 装饰器并更新 tasks.py 如:
from celery.task.schedules import crontab from celery.decorators import periodic_task @task def task1(): send_mail()
在celery.py中添加beat schedule为:
app.conf.beat_schedule = { 'alert': { 'task': 'app.tasks.task1', 'schedule': crontab(minute='15', hour='0, 7') }, 'custom_alert': { 'task': 'app.tasks.task1', 'schedule': crontab(minute='45', hour='15') } }
使用这些设置,task1() 中的 script 仅在所需时间触发(0:15,7:15 和 15:45)!