如何使Celery PeriodicTask在未来开始运行?

时间:2018-01-20 22:44:27

标签: python django celery django-celery celerybeat

我想创建一个周期性任务,但也想添加一个"开始时间"对于那个周期性任务。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以使用CELERYBEAT_SCHEDULE执行此操作。这是一个小例子(test.py):

from celery import Celery
from celery.schedules import crontab

celery = Celery(
    __name__,
    broker='redis://localhost:6379/0',
)


celery.conf.update(
    CELERY_RESULT_BACKEND='redis://localhost:6379/0',
    CELERY_IGNORE_RESULT=False,
    CELERY_ENABLE_UTC=True,
    CELERY_TASK_SERIALIZER='json',
    CELERY_RESULT_SERIALIZER='json',
    CELERYBEAT_SCHEDULE={
        'add-every-25': {
            'task': 'test.example',
            # use crontab to configure start time
            # run each 25th min
            'schedule': crontab(minute=25),
            # one more example - every Monday morning at 7:30 a.m.
            # 'schedule': crontab(hour=7, minute=30, day_of_week=1),
            'args': ()
        },
    },
)


@celery.task
def example():
    print('example was called')

运行我们的应用:

celery worker -A test.celery --loglevel=info -B
# when min == 25 you will see something like this:
[2018-01-31 18:25:00,030: WARNING/ForkPoolWorker-5] example was called
[2018-01-31 18:25:00,037: INFO/ForkPoolWorker-5] Task test.example[6bcbcf57-99df-4791-aaf4-1530eb8f25ba] succeeded in 0.00712332800322s: None

您也可以使用other parameters的crontab。

希望这有帮助。