gpt4 book ai didi

Django 是这个链接任务吗?

转载 作者:行者123 更新时间:2023-12-01 15:05:11 24 4
gpt4 key购买 nike

我有一个 celery 任务,可以像这样将消息添加到数据库中:

class ProcessRequests(Task):

def run(self, batch):

for e in q:
msg = Message.objects.create(
recipient_number=e.mobile,
content=batch.content,
sender=e.contact_owner,
billee=batch.user,
sender_name=batch.sender_name
)
gateway = Gateway.objects.get(pk=2)
msg.send(gateway)

然后在 msg.send(gateway) 模型中有另一个任务实际发送消息并运行它:

class SendMessage(Task):
name = "Sending SMS"
max_retries = 10
default_retry_delay = 3

def run(self, message_id, gateway_id=None, **kwargs):
logging.debug("About to send a message.")


so some stuff here

logging.debug("Done sending message.")

这一切都很好(测试了 1000 多条消息),但我在某处读到你不应该将任务链接在一起,但是这不是链接,对吧?我不会等到一个完成后另一个才能运行。

这个例子在性能等方面是否可以?

发送是这样的:

def send(self, message):
"""
Use this gateway to send a message.

If ``djcelery`` is installed, then we assume they have set up the
``celeryd`` server, and we queue for delivery. Otherwise, we will
send in-process.

.. note::
It is strongly recommended to run this out of process,
especially if you are sending as part of an HttpRequest, as this
could take ~5 seconds per message that is to be sent.
"""
if 'djcelery' in settings.INSTALLED_APPS:
import sms.tasks
sms.tasks.SendMessage.delay(message.pk, self.pk)
else:
self._send(message)

最佳答案

简短版本,是的,您在这里做的是正确的。

长版:

问题是你不想要这样的东西:

@task
def something(**kwargs):
# do something here
something_else.delay().get()

@task
def something_else(**kwargs):
# do something else here
pass

这将使 something 等待 something_else 的结果。

您甚至可以考虑将消息的创建转移到任务中(这样您的循环只会生成任务,不会直接连接到数据库)。

PS:如果您想跟踪 ProcessRequests 任务的所有结果,您可以将这些作为子结果执行:http://docs.celeryproject.org/en/latest/userguide/canvas.html?highlight=asyncresult#subtasks

它可以帮助您对结果进行分组:http://docs.celeryproject.org/en/latest/userguide/canvas.html?highlight=asyncresult#group-results

关于Django 是这个链接任务吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17219474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com