Skip to content

Instantly share code, notes, and snippets.

@pblocz
Created November 17, 2020 12:52
Show Gist options
  • Save pblocz/064d53a4b8c429117fd0479f48c1b63b to your computer and use it in GitHub Desktop.
Save pblocz/064d53a4b8c429117fd0479f48c1b63b to your computer and use it in GitHub Desktop.
'''
There are 2 types of functions normal `def func()` and `async def func()`:
- An asyc function can call async functions as well as normal ones
- A normal function can only call normal functions
'''
#%%
import asyncio
import datetime
async def main():
print("start", datetime.datetime.now())
await asyncio.sleep(3)
print("end", datetime.datetime.now())
return 5
async def more_main():
#%%
print("This will run one after the other")
coroutine = main() # Create the coroutine instance, it will not run it
await coroutine # Run the instance and wait for it
await main() # Create and run it directly
#%%
print("This will run in parallel")
task1 = asyncio.create_task(main()) # This starts the task directly in the background
task2 = asyncio.create_task(main())
await task1 # Wait for the result
await task2
#%%
print("This will also run in parallel")
await asyncio.gather(main(), main()) # The same, but for a list of coroutines
#%%
# This is necessary when running in a script to start the
# main async loop. You can have only one of these per thread.
coroutine = more_main()
asyncio.run(coroutine)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment