Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
added code example to keep strong references around
  • Loading branch information
agrommek committed May 26, 2022
commit 5148c7712904356d5a898940d6c3f677950513d5
18 changes: 17 additions & 1 deletion Doc/library/asyncio-task.rst
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,23 @@ Creating Tasks
Save a reference to the result of this function, to avoid
a task disappearing mid execution. The event loop only keeps
weak references to all task. Without a strong reference, the
task may get garbage-collected at any time.
task may get garbage-collected at any time. If you want to have
"fire-and-forget" background tasks you can do something like this::

# create an empty set to store references to background tasks
background_tasks = set()

# start 10 background tasks
for i in range(10):
task = asyncio.create_task(some_coro(param=i))

# Add task to set. This creates a strong reference.
background_tasks.add(task)

# To prevent accumulation of references to already finished
# tasks, make each task remove its own reference from set after
# completion:
task.add_done_callback(lambda t: background_tasks.discard(t))

.. versionadded:: 3.7

Expand Down