如何安排在月底运行的芹菜任务?

时间:2015-06-22 11:04:03

标签: python celery crontab

我需要设置芹菜crontab在月底运行,甚至在月末(28~31)的不同日期运行。 我知道如何在shell命令上设置crontab在月末运行,如下所示:

55 23 28-31 * * /usr/bin/test $( date -d '+1 day' +%d ) -eq 1 && exec something

但就芹菜时间表而言,我不知道如何进行此设置。 有没有办法安排在月底运行芹菜的任务?
似乎只能在is_due上覆盖celery.schedules.crontab方法。

2 个答案:

答案 0 :(得分:1)

如果您不介意一些开销 - 您可以将任务设置为每天在CELERYBEAT_SCHEDULE中运行。

然后在任务本身中,您可以检查该日是否是该月的最后一天:

import calendar
from datetime import datetime

@task
def task_to_run_at_end_of_month():
    today = datetime.today()
    day_in_month = today.day
    month = today.month
    year = today.year
    day_of_week, number_of_days_in_month = calendar.monthrange(year, month)
    if day_in_month != number_of_days_in_month:
        # not last day of month yet, do nothing
        return
    # process stuff on last day of month
    ...

答案 1 :(得分:0)

芹菜附带一个module就可以了。

从命令行运行它的方法就像这样

celery -A $project_name beat

通常情况下,您会使用worker代替beat

然后在celery_config.py中加入CELERYBEAT_SCHEDULE的定义。像这样的东西

from celery.schedules import crontab

CELERYBEAT_SCHEDULE = {
        "end_of_month_task": {
            "task": "module.task_name", # this is the task name
            "schedule": crontab(0, 0, day_of_month=0),
            "args": the_arguments_to_this_function
        }
    }
相关问题