Python Forum
How to add asynchronous tasks as they are needed?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to add asynchronous tasks as they are needed?
#1
As I understand, I can perform async- tasks in two ways:
1. Launch asynchronous tasks sequentially (the first task will be FULLY completed and then the second one):
2. Run several tasks in parallel:
Is it possible somehow, if I understand that tasks don't fully load the system, add more tasks? That is, to get dynamically change the load on the system.
Reply
#2
asyncio.run() should only be called once, as it creates a new event loop. The function asyncio.create_task() can add new coroutines to the event loop, so it'll be run *eventually* (probably whenever the event loop starts over, which might be almost immediately). https://docs.python.org/3/library/asynci...reate_task

Here's your first example, with an extra function added to help demonstrate:
import asyncio

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def speaker(message):
    for delay in range(3):
        await say_after(delay, message)

async def main():
    await say_after(1, "hello")
    await say_after(2, "world")
    task = asyncio.create_task(speaker("extra work"))
    await say_after(1, "hello 2")
    await say_after(2, "world 2")
    await task

if __name__ == "__main__":
    asyncio.run(main())
Output:
hello world extra work hello 2 extra work world 2 extra work
Reply
#3
nilamo, thank you!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  drawing a table with the status of tasks in each thread pyfoo 3 414 Mar-01-2024, 09:29 AM
Last Post: nerdyaks
  How to script repetitive tasks in dynaform using python BenneGrus 0 1,343 Dec-22-2021, 08:36 AM
Last Post: BenneGrus
  asyncio: executing tasks + httpserver freebsdd 2 2,641 Aug-29-2020, 09:50 PM
Last Post: freebsdd
  How I can limit quantity of parallel executable tasks in asyncio? AlekseyPython 1 2,426 Oct-24-2018, 10:22 AM
Last Post: AlekseyPython
  run two tasks concurrently tony1812 1 2,608 Jul-24-2017, 05:43 PM
Last Post: Larz60+
  Tasks for Python Lamon112 2 37,275 Jan-13-2017, 03:32 AM
Last Post: metulburr
  Asynchronous Logging in python 2.7 Elbi 4 8,493 Oct-09-2016, 06:10 PM
Last Post: Elbi

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020