How to run a Django celery task every 6am and 6pm daily?
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)
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'))