【问题标题】:How to run the functions periodically while main is waiting for the server close如何在 main 等待服务器关闭时定期运行函数
【发布时间】:2021-02-04 16:00:59
【问题描述】:

我有 C 编程经验和 Python 新手。我想连续运行 fucntion1 和 fucntion2 而不是等待服务器关闭。现在下面的代码运行一次函数并等待服务器。如何运行函数?请帮忙

async def main():
    function1()
    function2()
    server = await websockets.serve(
        on_connect,
        '192.168.1.251',
        9000,
        subprotocols=['ocpp1.6'],
        ping_interval = 10,
        ping_timeout = 120
        )
    logging.info("Server Started listening to new connections...")
    await server.wait_closed()

【问题讨论】:

  • 感谢您的快速回复。我会在这里验证和更新
  • 我添加了代码并启动了线程,但它只运行了一次。我正在打印一些在输出中只能看到一次的文本。
  • asyncio 你可以运行多个任务。 docs.python.org/3/library/…
  • 我想重复运行这些函数。我尝试使用 await 和 async 进行更改,但我仍然只能看到一次输出,并且套接字服务器正在运行直到它关闭。

标签: python async-await


【解决方案1】:

您可以在两个单独的线程中运行函数 1 和 2。

from threading import Thread
t1 = Thread(target = function1)
t2 = Thread(target = function2)
t1.setDaemon(True)
t2.setDaemon(True)
t1.start()
<your code to connect to server>

【讨论】:

    【解决方案2】:

    我通过使用调度模块解决了这个问题

    导入 aioschedule 作为计划 schedule.every(10).seconds.do(func,parameters)

    asyncio.run(schedule.run_pending)

    希望这可以帮助某人。感谢大家提出宝贵的建议。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-20
      • 1970-01-01
      • 2013-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多