[Fixed]-Django celery crontab every 30 seconds – is it even possible?


Very first example they have in the documentation is

Example: Run the tasks.add task every 30 seconds.

from datetime import timedelta

    "runs-every-30-seconds": {
        "task": "tasks.add",
        "schedule": timedelta(seconds=30),
        "args": (16, 16)


You could just use

from datetime import timedelta

def thirty_second_task():
   now = datetime.now()
   if now.hour == 12 or now.hour == 9:
       your code goes here`

That will run the function every thirty seconds, but it will only run your code if the hour value of the current time is 12 or 9.


If you really need to do this and you need a solution quickly, you could resort to adding:
sleep <num_seconds>
into your script.
(obviously you’d need to add a parameter to your script to setup the sleep time to either 0 or 30 seconds and add the script twice to crontab, once with 0 as the parameter, secondly with 30).



I would go with your alternative solution by scheduling another task to enable/disable the primary task:

# tasks.py
from djcelery.models import PeriodicTask

def toggle_thirty_second_task:
    # you would use whatever you named your task below
    thirty_second_tasks = PeriodicTask.objects.filter(name='runs-every-30-seconds')
    if thirty_second_tasks:
        # this returned an array, so we'll want to look at the first object
        thirty_second_task = thirty_second_tasks[0]
        # toggle the enabled value
        thirty_second_task.enabled = not thirty_second_task.enabled

Then just schedule this task using a crontab for the hours that you need to toggle. Alternatively, you could have a task scheduled to turn it on and one to turn it off and not deal with the toggling logic.

Hope this helps.


Leave a comment