Loading... > 利用asyncio异步 实现多个任务的循环异步执行 **循环中既包括同步函数也包括异步协程** * 核心思想: 将所有任务注册到event_loop中: * 对于异步协程任务内部利用while循环不断执行, 本身就是非阻塞的 * 对于函数, 利用loop.call_later递归调用来实现非阻塞循环 ```python /# And the mixed one —————————/ *import*asyncio *import*time *def*hello_world(loop): print(*’Hello World’*) loop.call_later(1, hello_world, loop) *def*good_evening(loop): print(*’Good Evening’*) loop.call_later(1, good_evening, loop) @asyncio.coroutine *def*hello_world_coroutine(): *while True*: *yield from*asyncio.sleep(1) print(*’Hello World Coroutine’*) @asyncio.coroutine *def*good_evening_coroutine(): *while True*: *yield from*asyncio.sleep(1) print(*’Good Evening Coroutine’*) print(*’step: asyncio.get_event_loop()’*) loop = asyncio.get_event_loop() print(*’step: loop.call_soon(hello_world, loop)’*) loop.call_soon(hello_world, loop) print(*’step: loop.call_soon(good_evening, loop)’*) loop.call_soon(good_evening, loop) print(*’step: asyncio.async(hello_world_coroutine)’*) loop.create_task(hello_world_coroutine()) print(*’step: asyncio.async(good_evening_coroutine)’*) loop.create_task(good_evening_coroutine()) *try*: loop.run_forever() *except*KeyboardInterrupt: *pass* *finally*: print(*’step: loop.close()’*) loop.close() ``` © 允许规范转载