如何使用Celery调度每月1日运行的任务?

16 投票
3 回答
10259 浏览
提问于 2025-04-16 08:17

我想知道怎么用来安排一个每个月1号运行的任务,该怎么做呢?

3 个回答

0

在你的应用配置文件中,使用下面的 crontab 来设置 Celery 的定时任务调度器:

crontab(hour=set_your_hours, minute=set_your_minutes, day_of_week="*",
        day_of_month=1, month_of_year="*")
10

你可以使用 Crontab计划 来实现这个功能,你可以在以下两个地方定义它:

  • 在你的django settings.py 文件中:
from celery.schedules import crontab

CELERYBEAT_SCHEDULE = {
    'my_periodic_task': {
        'task': 'my_app.tasks.my_periodic_task',
        'schedule': crontab(0, 0, day_of_month='1'), # Execute on the first day of every month.
    },
}
  • celery.py 配置文件中:
from celery import Celery
from celery.schedules import crontab

app = Celery('app_name')
app.conf.beat_schedule = {
    'my_periodic_task': {
        'task': 'my_app.tasks.my_periodic_task',
        'schedule': crontab(0, 0, day_of_month='1'), # Execute on the first day of every month.
    },
}
17

从Celery 3.0版本开始,crontab的调度现在支持 day_of_month(每月的某一天)和 month_of_year(每年的某个月)这两个参数:http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#crontab-schedules

撰写回答