|
发表于 2023-5-8 16:52:19
|
显示全部楼层
你可以使用 asyncio.sleep() 方法来实现异步计时器。下面是修改后的代码:
- import asyncio
- async def my_event_handler(event):
- global t_result
- global stop_condition
- stop_condition = True
- ply = event.text
- t_result = {as:ply}
- await client.disconnect()
- return stop_condition, t_result
- async def timer():
- # 计时器代码
- global t_result
- global stop_condition
- await asyncio.sleep(5)
- stop_condition = False
- print("timer Exception")
- await client.disconnect()
- t_result = {as:"超时,请稍后重试!"}
- return stop_condition, t_result
- loop = asyncio.get_event_loop()
- tasks = [loop.create_task(my_event_handler(event)), loop.create_task(timer())]
- done, pending = loop.run_until_complete(asyncio.wait(tasks, timeout=5))
- if len(done) == 0:
- # 超时处理
- stop_condition = False
- t_result = {as:"超时,请稍后重试!"}
- else:
- # 处理结果
- for task in done:
- stop_condition, t_result = task.result()
- loop.close()
- return stop_condition, t_result
复制代码
这里使用 asyncio.wait() 方法来同时等待事件处理和计时器任务的完成,设置超时时间为 5 秒。如果在超时时间内没有完成任务,则返回超时提示。如果完成了任务,则返回任务的结果。 |
|