如何每天早上6点和下午6点运行Django芹菜任务?

时间:2015-09-08 05:27:29

标签: python django django-celery periodic-task

嗨,我的项目中有Django Celery。目前每天运行12小时(午夜/ 00:00和12:00 pm)。但我希望它每天早上6点和下午6点运行。我怎样才能做到这一点?提前谢谢。

任务:

from celery.task import periodic_task
from celery.schedules import crontab  
from xxx.views import update_xx_task, execute_yy_task

@periodic_task(run_every=crontab(minute=0, hour='*/12'),
    queue='nonsdepdb3115', options={'queue': 'nonsdepdb3115'})
def xxx_execute_xx_task():
    execute_yy_task()
    update_xx_task()

2 个答案:

答案 0 :(得分:7)

documentation,在示例表中,您可以看到您可以传递多个小时(24小时内)。所以,因为你想在早上6点和下午6点(1800)运行它:

@periodic_task(run_every=crontab(minute=0, hour='6,18'))

答案 1 :(得分:1)

最好这样做:

在您的celery.py文件中

import os

from celery import Celery
from celery.schedules import crontab

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Moex.settings')

app = Celery('Moex',
             backend='rpc://',
             broker='pyamqp://', )

app.config_from_object('django.conf:settings', namespace='CELERY', )

app.conf.update(result_expires=3600,
                enable_utc=True,
                timezone='Europe/Moscow', )

app.conf.beat_schedule = {
    "every day between 6 AM & 18 PM": {
        "task": "xxx_execute_xx_task",  # <---- Name of task
        "schedule": crontab(hour='6, 18',
                            minute=0,
                            )
    },
    "every minute": {
        "task": "check_if_need_update_prices",
        'schedule': 60.0,
    }
}

app.autodiscover_tasks()

然后在您的task.py文件中

import requests
from celery import shared_task, states


@shared_task(bind=True,
             name='xxx_execute_xx_task',
             max_retries=3,
             soft_time_limit=20)
def xxx_execute_xx_task(self):
    # do something
    data = requests.get(url='https://stackoverflow.com/questions/32449845/'
                            'how-to-run-a-django-celery-task-every-6am-and-6pm-daily')
if data.status_code == 200:
    task.update_state(state=states.SUCCESS)
    if data:
        self.update_state(state=states.SUCCESS)
    else:
        self.update_state(state=states.FAILURE)