关于asyncio.create_task异步并发执行的研究

发布时间 2023-11-10 19:41:23作者: pywjh

关于asyncio.create_task异步并发执行的研究

# 不在乎结果版本

async def do_some_thing(a, b):
    time.sleep(3)
    print(f"{datetime.datetime.now()} handle do_some_thing with a:{a} and b:{b}")
    return a + b


class TaskHandler(tornado.web.RequestHandler):
    async def get(self):
        print(f'{datetime.datetime.now()} start TaskHandler')
        res = asyncio.create_task(do_some_thing(1, 2))
        print(f'{datetime.datetime.now()} end TaskHandler')
        self.write("success")
        print(f"write success time: {datetime.datetime.now()}")


def make_app():
    return tornado.web.Application([
        (r"/task", TaskHandler),
    ])


if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()
    

# 2023-11-10 19:34:41.035492 start TaskHandler
# 2023-11-10 19:34:41.035519 end TaskHandler
# write success time: 2023-11-10 19:34:41.035529
# 2023-11-10 19:34:44.040885 handle do_some_thing with a:1 and b:2
# 等待结果

async def do_some_thing(a, b):
    time.sleep(3)
    print(f"{datetime.datetime.now()} handle do_some_thing with a:{a} and b:{b}")
    return a + b


class TaskHandler(tornado.web.RequestHandler):
    async def get(self):
        print(f'{datetime.datetime.now()} start TaskHandler')
        res = asyncio.create_task(do_some_thing(1, 2))
        print(f'{datetime.datetime.now()} end TaskHandler')
        await res
        print(f"{datetime.datetime.now()} res.result(): {res.result()}")
        self.write("success")
        print(f"write success time: {datetime.datetime.now()}")


def make_app():
    return tornado.web.Application([
        (r"/task", TaskHandler),
    ])


if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()
    
# 2023-11-10 19:36:40.486563 start TaskHandler
# 2023-11-10 19:36:40.486649 end TaskHandler
# 2023-11-10 19:36:43.491812 handle do_some_thing with a:1 and b:2
# 2023-11-10 19:36:43.492300 res.result(): 3
# write success time: 2023-11-10 19:36:43.492461