【发布时间】:2022-11-22 09:32:00
【问题描述】:
我正在尝试制作一个 UDP 服务器,在它旁边是一个周期性任务,每 5 分钟更新一个全局变量。
但问题是我的 UDP 服务器和我的任务部分阻止了其余代码(因为我使用 while true)。
我在看这个例子: https://docs.python.org/3/library/asyncio-protocol.html#asyncio-udp-echo-server-protocol
import asyncio
class EchoServerProtocol:
def connection_made(self, transport):
self.transport = transport
def datagram_received(self, data, addr):
message = data.decode()
print('Received %r from %s' % (message, addr))
print('Send %r to %s' % (message, addr))
self.transport.sendto(data, addr)
async def main():
print("Starting UDP server")
# Get a reference to the event loop as we plan to use
# low-level APIs.
loop = asyncio.get_running_loop()
# One protocol instance will be created to serve all
# client requests.
transport, protocol = await loop.create_datagram_endpoint(
lambda: EchoServerProtocol(),
local_addr=('127.0.0.1', 9999))
try:
await asyncio.sleep(3600) # Serve for 1 hour.
finally:
transport.close()
asyncio.run(main())
我在示例中看到他们运行了一个小时。但是如果我想无限期地运行它呢?我玩过 run_forever() 但我不明白它是如何工作的。
我也不明白如何制作一个不同时使用 while true 的周期性任务。这可能吗?
【问题讨论】:
标签: python python-asyncio