Home > front end >  Asyncio : how to run one task in another one concurrently?
Asyncio : how to run one task in another one concurrently?

Time:11-06

I have two functions, both are async and they run outside a function thanks to asyncio
However, the second function is inside the first one, and it's blocking the execution of the first :
(note that this needs to be compatible with most used Python versions, from 3.8 to latest one)

async def func_2():
  # basically does a request to a website and returns the status code

async def func_1():
  tab = ["el0", "el1", ..., "el10"]  
  for i in range(len(tab)):
    sys.stdout.write("\r[∆] Progress: "   tab[i % len(tab)])
    sys.stdout.flush()
    if i == 1:
      result = await func_2()
    await asyncio.sleep(0.4)
  return result

while True: 
  func = asyncio.get_event_loop()
  func_coroutine = func_1()
  result = anim.run_until_complete(func_coroutine)
  if result == 200:
    print("Up")
  else:
    print("Down")

The func_1() is just here to make the user wait, but the func_2() does the real job, and takes way more time than 0.4 seconds

  • Related