Virat
Virat

Reputation: 129

Running tasks in Django Celery at specified time?

Snippet from my tasks.py file are as follows:

from celery.task.schedules import crontab
from celery.decorators import periodic_task

@periodic_task(
    run_every=crontab(minute='15, 45', hour='0, 7, 15'),
)
def task1():
    send_mail()

I want the script in task1() to be triggered only at 00:15, 7:15 and 15:45, whereas with the current settings it's triggered at 00:15, 00:45, 7:15, 7:45, 15:15 and 15:45.

How do I do this ? Also, let me know if there is a better approach!

Upvotes: 0

Views: 817

Answers (2)

Virat
Virat

Reputation: 129

After reading through the documentation, and borrowing some ideas from here, I went about solving this as follows:

  1. Removing the periodic_task decorator and updating the tasks.py as:

    from celery.task.schedules import crontab
    from celery.decorators import periodic_task
    
    @task
    def task1():
        send_mail()
    
  2. Add the beat schedule in celery.py as:

    app.conf.beat_schedule = {
        'alert': {
            'task': 'app.tasks.task1',
            'schedule': crontab(minute='15', hour='0, 7')
        },
        'custom_alert': {
            'task': 'app.tasks.task1',
            'schedule': crontab(minute='45', hour='15')
        }
    }
    

With these settings, the script in task1() is getting triggered only at desired time (0:15, 7:15 and 15:45)!

Upvotes: 1

schillingt
schillingt

Reputation: 13731

You have two options. One is to define the decorated function a few times:

def _task1():
    send_mail()

task1_a = @periodic_task(
    _task1,
    run_every=crontab(minute='15', hour='0, 7'),
)
task1_b = @periodic_task(
    _task1,
    run_every=crontab(minute='45', hour='15'),
)

The other option is to define a custom schedule implementing celery's schedule interface.

Upvotes: 0

Related Questions