Django通道组发送之间的睡眠



我试图实现的目标非常简单,因为你可以在标题中阅读,但我无法让它发挥作用"在两次发送之间休眠";。我的代码:

await self.channel_layer.group_send(
str(self.game_link),
{
"type": "group_message",
"text": json.dumps(answer_data),
}
)
await asyncio.sleep(5)
await self.channel_layer.group_send(
str(self.game_link),
{
"type": "group_message",
"text": json.dumps(data),
}
)

这里发生的情况是,在睡眠结束后,两者同时发送。

经过一番搜索和阅读这篇SO文章,我终于成功了。

简短回答

await asyncio.sleep(5)放入group_message方法

解释

在等待group_send时,该过程不是立即发送消息,而是发送到队列(对于组中的所有成员(。

由于此过程尚未完成,因此此通道在某种程度上被阻塞,无法使用未来的消息。进程必须休眠5秒,等待另一个group_send,然后最终在自己的队列中使用这两条消息。

如果您从其他地方加入群(例如打开另一个浏览器(,您将在延迟5秒后收到第二条消息。

另一方面,将await asyncio.sleep(5)放在group_message中,只会在消费消息时休眠。

注意:添加一个过滤逻辑,使不是所有消息都进入睡眠

async def group_message(self, data):
if 'sleep' in data:
await asyncio.sleep(data.pop('sleep'))
await self.send(text_data=data['text'])

在你的信息发送者:

await self.channel_layer.group_send(
str(self.game_link),
{
"type": "group_message",
"text": json.dumps(data),
}
)
# second message: sleep before send
await self.channel_layer.group_send(
str(self.game_link),
{
"type": "group_message",
"text": json.dumps(data),
"sleep": 5
}
)

相关内容

最新更新