celerybeat how to pass arguments via scheduler to functions?
Asked Answered
S

2

8

im having trouble passing arguments to my functions via celerybeat schedule. After searching it looks as though I should be able to pass them with the args command but im getting errors as per the below. can anyone point me in the right direction?

CELERYBEAT_SCHEDULE = {
    'maintenance_mail_1_day': {
        'task': 'home.tasks.maintenance_mail',
        'schedule': crontab(hour='15'),
        'args' : (1),
    },
    'maintenance_mail_3_day': {
        'task': 'home.tasks.maintenance_mail',
        'schedule': crontab(hour='15'),
        'args' : (3),
    },    
    'maintenance_mail_5_day': {
        'task': 'home.tasks.maintenance_mail',
        'schedule': crontab(hour='15'),
        'args' : (5),
    },
    'maintenance_mail_7_day': {
        'task': 'home.tasks.maintenance_mail',
        'schedule': crontab(hour='15'),
        'args' : (7),
    }

tasks,py

@app.task
def maintenance_mail(days):
    return send_maintnance_emails(days)
Sofer answered 5/10, 2017 at 12:28 Comment(2)
What errors do you get?Hertz
Args must be a tuple: do 'args' : (1,) (note the extra comma)Brechtel
B
12

The following holds in Python: (1) == 1

In order to make it a singleton tuple, add an extra comma: (1,) and in your settings accordingly:

# ...
'args' : (1,),
# ...
Brechtel answered 5/10, 2017 at 12:34 Comment(0)
C
0

You can specify the arguments and keyword arguments used to execute the task as follows. Note how JSON serialization is required.

import json

CELERYBEAT_SCHEDULE = {
    'maintenance_mail_1_day': {
        'task': 'home.tasks.maintenance_mail',
        'schedule': crontab(hour='15'),
        'args' : json.dumps([1]),
    }
}

OR

import json

CELERYBEAT_SCHEDULE = {
    'maintenance_mail_1_day': {
        'task': 'home.tasks.maintenance_mail',
        'schedule': crontab(hour='15'),
        'kwargs' : json.dumps({
            'days': 1,
        }),
    }
}

More info here: django-celery-beat documentation

Cerement answered 4/4, 2022 at 13:35 Comment(1)
The docs you link to are for django-celery-beat talking about adding rows into the table. The config that OP mentioned requires 'args' to be a tuple or a list and 'kwargs' to be a dict: docs.celeryq.dev/en/stable/userguide/…Unappealable

© 2022 - 2024 — McMap. All rights reserved.