Sync tasks in loop - Async Python
Keyboard shortcuts
Press ← or → to navigate between chapters
Press S or / to search in the book
Press ? to show this help
Press Esc to hide this help
Sync tasks in loop
In this example too we’ll use sleep to pretend we are waiting for some external task to finish, but this time we’ll start a number of jobs based on what the user supplies.
We can’t know up-front how many tasks we’ll have to call.
Code
import time
import sys
def do_task(task_id: int, sec: int):
print(f"Start task {task_id}")
time.sleep(sec)
print(f"End task {task_id}")
def main():
if len(sys.argv) != 2:
exit(f"Usage {sys.argv[0]} NUMBER")
for i in range(int(sys.argv[1])):
do_task(i, 1)
start = time.monotonic()
main()
end = time.monotonic()
print(f"Elapsed time: {end-start}")
Output
Start task 0
End task 0
Start task 1
End task 1
Start task 2
End task 2
Start task 3
End task 3
Elapsed time: 4.000992348068394
As one could expect from such code, the total time required for such program to run is the sum of all the tasks as they run sequentially.