简体   繁体   English

Django-使用选项但不使用函数参数执行Celery任务

[英]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. 查看文档,似乎我已经尝试了所有事情来使用apply_async正确执行任务。 I'm calling the task from a signal method so it's in signals.py. 我正在从信号方法调用任务,因此它位于signal.py中。

signals.py signal.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 task.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 . 代码运行时,出现错误: 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. 我尝试了各种方法来编写使用apply_async调用任务的行,但没有任何效果。 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: 当您使用bind=True关键字参数时,您的任务将获得对自身的引用,因此将方法签名更改为:

def sendSMS_Scheduled(self):

As a side note, keep in mind that self in this context is the actual celery task. 作为一个侧面说明,请记住,在这种情况下, self是实际的芹菜任务。 You have a line self.request.sms_set.all() which makes me think you are expecting self to be something django specific. 您有一行self.request.sms_set.all() ,这使我认为您期望self是特定于Django的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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