You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
37 lines
972 B
Python
37 lines
972 B
Python
3 years ago
|
import asyncio
|
||
|
import time
|
||
|
|
||
|
|
||
|
async def main():
|
||
|
print(f"{time.ctime()} Hello!")
|
||
|
await asyncio.sleep(1.0)
|
||
|
print(f"{time.ctime()} Goodbye!")
|
||
|
loop.stop()
|
||
|
|
||
|
|
||
|
def blocking():
|
||
|
# This code only works because our blocking sleep is less than the main functions Asyncio sleep call. If
|
||
|
# this function used here was time.sleep(2) then we would get a RuntimeError because the eventloop was
|
||
|
# Already closed when the Future's job completed
|
||
|
time.sleep(0.5)
|
||
|
print(f"{time.ctime()} Hello from thread!")
|
||
|
|
||
|
|
||
|
loop = asyncio.get_event_loop()
|
||
|
|
||
|
loop.create_task(main())
|
||
|
# Returns a asyncio Future not a asyncio Task
|
||
|
loop.run_in_executor(None, blocking)
|
||
|
|
||
|
loop.run_forever()
|
||
|
|
||
|
# Deprecated Style
|
||
|
# pending = asyncio.Task.all_tasks(loop=loop)
|
||
|
pending = asyncio.all_tasks(loop=loop)
|
||
|
|
||
|
# asyncio.gather also returns a future
|
||
|
group = asyncio.gather(*pending)
|
||
|
print(f"The type returned of asyncio.gather is: {type(group)}")
|
||
|
loop.run_until_complete(group)
|
||
|
loop.close()
|