I need to set celery crontab to run at the end of month even different day as end of month(28~31). I know how to set crontab run at the end of month on shell command like this:
55 23 28-31 * * /usr/bin/test $( date -d '+1 day' +%d ) -eq 1 && exec something
But on celery schedule I don't know how to do this setting. Is there any way to schedule task which runs at the end of month on celery?
It seems only way is to override is_due
method on celery.schedules.crontab
.
If you don't mind a bit of overhead - you can set the task to run every day in CELERYBEAT_SCHEDULE.
And then in the task itself you can check if the day is the last day of the month:
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
...
Celery comes with a module that does exactly this.
The way to run it from the command line is like this
celery -A $project_name beat
Where normally you would use worker
instead of beat
Then include in your celery_config.py
a definition of the CELERYBEAT_SCHEDULE
. Something like this
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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.