celerybeat how to pass arguments via scheduler to functions?

Viewed 3765

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)
2 Answers

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,),
# ...

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

Related