欢迎访问宙启技术站
智能推送

celery.schedulescrontab():创建自定义的定时任务规则

发布时间:2023-12-23 23:01:16

celery.schedules.crontab() 是 Celery 库中用于创建自定义定时任务规则的函数。它允许我们根据 crontab 表达式来定义任务的执行时间。

crontab 是用来在 Unix/Linux 系统上设置定期执行任务的命令。它的语法如下:

* * * * * command
- - - - -
| | | | |
| | | | ----- Day of the Week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of the Month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)

首先,我们需要导入 celerycelery.schedules

from celery import Celery
from celery.schedules import crontab

然后,我们可以在 Beat Schedule(一个用于定时执行任务的配置文件)中使用 crontab() 函数来创建自定义任务规则。例如,我们可以定义一个每天上午10点执行一次的定时任务:

app.conf.beat_schedule = {
    'execute_task': {
        'task': 'my_task',
        'schedule': crontab(hour=10, minute=0),
    },
}

在上面的示例中,我们给任务命名为 'execute_task',指定了要执行的任务名为 'my_task',并且将任务规则设置为每天上午10点。

我们还可以通过传递额外的参数来细化任务的执行时间。例如,我们可以定义一个在每月的第一天和第十五天上午10点执行的定时任务:

app.conf.beat_schedule = {
    'execute_task': {
        'task': 'my_task',
        'schedule': crontab(hour=10, minute=0, day_of_month='1,15'),
    },
}

在上面的示例中,我们向 crontab() 函数传递了 day_of_month='1,15' 参数,这意味着任务将在每个月的第一天和第十五天执行。

除了 day_of_monthcrontab() 函数还接受其他参数以细化任务的执行时间,包括 month_of_year(月份)、day_of_week(星期几)、hour(小时)和 minute(分钟)。可以将这些参数与适当的值传递给 crontab() 函数以定义自定义的任务规则。

希望上述信息可以帮助到您使用 celery.schedules.crontab() 函数来创建自定义的定时任务规则。