繁体   English   中英

Asyncio.sleep() 似乎永远沉睡

[英]Asyncio.sleep() seems to sleep forever

我需要编写 function ,它将 object 添加到数组并在 x 秒后将其删除。 我使用 asyncio.sleep 进行延迟。 这是代码:

import asyncio


class Stranger: 
    def __init__(self, address):
        self.address = address 


class Fortress:  
    def __init__(self, time_: int, attempts: int):
        self.time = time_ 
        self.attempts = attempts 
        self.strangers_list: list = []

    async def _handle_task(self, stranger):  
        self.strangers_list.append(stranger)
        index = len(self.strangers_list) - 1
        await asyncio.sleep(self.time)
        print('Woke up')
        self.strangers_list.pop(index)

    async def _create_handle_task(self, stranger): 
        task = asyncio.create_task(self._handle_task(stranger))
        print('Ran _handle_task')

    def handle(self, stranger): 
        asyncio.run(self._create_handle_task(stranger))


async def main(tim):
    await asyncio.sleep(tim)


if __name__ == "__main__":
    f = Fortress(2, 4)
    s = Stranger('Foo street, 32')
    f.handle(s)
    asyncio.run(main(3))

理论上,output 可能是:

Ran _handle_task
Woke up

但只是Ran _handle_task干扰程序从睡眠中出来的问题是什么?

您已经创建了一个任务,这是awaitable中可等待的示例。 您需要在_create_handle_task方法中await task

async def _create_handle_task(self, stranger): 
    task = asyncio.create_task(self._handle_task(stranger))
    
    await task 
    # ^blocks until the task is complete.
    
    print('Ran _handle_task')

来源:异步文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM