Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python async function

import asyncio
import time


async def say_after(delay, msg):
   """
   :param delay: how many seconds to delay
   :param msg: message to print to console
   :return: msg
   """
   await asyncio.sleep(delay)
   print(msg)
   return msg


async def main():
   print(f"started at {time.strftime('%X')}")
   # execute async functions concurrently and return the results as a list
   results = await asyncio.gather(say_after(delay=3, msg='hello'), say_after(delay=1, msg='world'))
   print(f"finished at {time.strftime('%X')}")
   print(f"Results of async gather {results}")

# run async main function
asyncio.run(main())

# output
# started at 16:57:46
# world
# hello
# finished at 16:57:49
# Results of async gather ['hello', 'world']
Source by codefreelance.net #
 
PREVIOUS NEXT
Tagged: #python #async #function
ADD COMMENT
Topic
Name
7+7 =