【问题标题】:How can I make a non-blocking UDP server and a periodic task in the same script?如何在同一脚本中制作非阻塞 UDP 服务器和周期性任务?
【发布时间】: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


    【解决方案1】:

    用等待永远不会发生的asyncio.Event替换你的asyncio.sleep(3600)。这将永远暂停任务,但让事件循环继续运行。终止程序的唯一方法是使用 Ctrl-C 或其他操作系统操作。

    try:
        await asyncio.Event().wait()  # wait here until the Universe ends
    finally:
        transport.close()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-03
      • 2021-04-03
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多