如何使用celery安排任务在特定时间执行?

19 投票
4 回答
28868 浏览
提问于 2025-04-15 17:32

我查了一下 PeriodicTask,但是里面的例子只讲了怎么让任务重复执行。我想要的是更像 cron 的功能,比如说“每周一早上1点执行这个任务”。

4 个回答

6

我刚刚提交了一个补丁,目的是增加一个定时任务,这样可以实现基于时间的调度,而不是基于周期的调度:

https://github.com/celery/celery/commit/e8835f1052bb45a73f9404005c666f2d2b9a9228

38

使用

YourTask.apply_async(args=[some, args, here], eta=when)

在你的任务结束时,重新安排它在下次应该运行的时间。

32

最近发布的1.0.3版本现在支持这个功能,感谢Patrick Altman的贡献!

示例:

from celery.task.schedules import crontab
from celery.decorators import periodic_task

@periodic_task(run_every=crontab(hour=7, minute=30, day_of_week="mon"))
def every_monday_morning():
    print("This runs every Monday morning at 7:30a.m.")

想了解更多信息,可以查看更新日志:

http://celeryproject.org/docs/changelog.html

撰写回答