简体   繁体   中英

Django - Execute Celery task with options but no function arguments

I'm using Celery for the first time. Looking at the documentation, it seems like I've tried everything to properly execute the task using apply_async. I'm calling the task from a signal method so it's in signals.py.

signals.py

from django.db.models.signals import post_save
from django.dispatch import receiver
from datetime import datetime, timedelta

from games.models import Game
from contacts.models import Contact
from msgs.models import SMS
from msgs.tasks import sendSMS_Scheduled


@receiver(post_save, sender=Game)
def createSMS(sender, instance, created, **kwargs):

    if created:

        contacts = Contact.objects.all()
        body = SMS.defaultMessageBuilder(
            location=instance.location,
            time=instance.schedStart
        )
        eta = instance.schedStart - timedelta(hours=7)
        expire = instance.schedStart
        result = sendSMS_Scheduled.apply_async(eta=eta, expires=expire)

tasks.py

from celery import shared_task
from SMSerSite.celery import app
from contacts.models import Contact

from .models import SMS

@shared_task(name='SMSerSite.msgs.tasks.sendSMS', bind=True)
def sendSMS_Scheduled():

    messages = self.request.sms_set.all()

    SMS.sendSMS(messages)

When the code runs, I get an error: sendSMS_Scheduled() takes 0 positional arguments but 1 was given . I've tried various ways of writing the line where I call the task using apply_async but nothing works. What am I getting wrong here?

When you use the bind=True keyword argument, your task gets a reference to itself, so change your method signature to:

def sendSMS_Scheduled(self):

As a side note, keep in mind that self in this context is the actual celery task. You have a line self.request.sms_set.all() which makes me think you are expecting self to be something django specific.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM