如何确保立即发送Django Channels消息而没有延迟? [英] How do I ensure a Django Channels message is sent immediately without delay?
问题描述
这个想法是在 worker.connect
worker上运行一个后台任务。在执行任务时,我想通过通知组将其进度发送给连接的客户端。
The idea is to run a background task on the worker.connect
worker. While executing the task, I would like to send its progress to a connected client via the notifications Group.
问题:发送到通知组的消息被延迟到工人的任务已完成。因此:延迟5秒( sleep(5)
)后,开始和停止这两个消息同时出现在客户端上。我希望消息开始,然后延迟5秒,然后消息停止。知道为什么不是这种情况吗?
The problem: the messages sent to the notifications Group are delayed until the task on the worker is finished. So: both messages 'Start' and 'Stop' appear simultaneously on the client, after a delay of 5 seconds (sleep(5)
). I would expect the message 'Start', followed by a 5sec delay, followed by the message 'Stop'. Any idea why this is not the case?
我正在运行以下三个进程:
I have the following three processes running:
-
daphne tests.asgi:channel_layer
-
python manage.py runworker --exclude-channel = worker.connect
-
python manage.py runworker --only-channel = worker.connect
daphne tests.asgi:channel_layer
python manage.py runworker --exclude-channel=worker.connect
python manage.py runworker --only-channel=worker.connect
在 views.py
:
def run(request, pk):
Channel('worker.connect').send({'pk': pk})
return HttpResponse(status=200)
在 consumers.py
:
def ws_connect(message):
Group('notifications').add(message.reply_channel)
message.reply_channel.send({"accept": True})
def worker_connect(message):
run_channel(message)
在 views.py
:
def run_channel(message):
Group('notifications').send({'text': 'Start'})
sleep(5)
Group('notifications').send({'text': 'Stop'})
routing.py
channel_routing = {
'websocket.connect': consumers.ws_connect,
'worker.connect': consumers.worker_connect,
}
推荐答案
您可以将 immediately = True
添加为 send
函数的参数。根据消息来源:
You can add immediately=True
as argument to the send
function. According to the source:
发送被延迟到消费者完成为止。要覆盖它,您可以立即传递= True。
Sends are delayed until consumer completion. To override this, you may pass immediately=True.
https://github.com/django/channels/blob/master/channels/channel.py#L32
这篇关于如何确保立即发送Django Channels消息而没有延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!