18

Hi I have Django Celery in my project. Currently its running every 12hour a day (Midnight/00:00am and 12:00pm). But I want it to run every 6am and 6pm a day. How can I do that? Thanks in advance.

Task:

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()
blackwindow
  • 437
  • 1
  • 8
  • 25

2 Answers2

33

From the documentation, in the examples table - you can see that you can pass in multiple hours (in 24 hour time). So, as you want to run it at 6 AM and 6 PM (1800):

@periodic_task(run_every=crontab(minute=0, hour='6,18'))
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
7

Better do this by the way:

In your celery.py file

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()

Then in your tasks.py file

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)
Kirill Vladi
  • 484
  • 6
  • 14