Skip to content

Instantly share code, notes, and snippets.

@jomido
Last active November 19, 2021 13:12
Show Gist options
  • Save jomido/13811370557c97e94f7dd42726b96ecb to your computer and use it in GitHub Desktop.
Save jomido/13811370557c97e94f7dd42726b96ecb to your computer and use it in GitHub Desktop.
# fire-n-forget
#
# https://bugs.python.org/issue44665
# https://bugs.python.org/issue42538
import asyncio
import functools
running_tasks = set()
def on_done(task, n):
print("done task " + str(n))
exception = None
try:
exception = task.exception()
except asyncio.CancelledError:
pass
if exception:
# do something other than print the exception
print(exception)
running_tasks.remove(task)
print(f"{len(running_tasks)} tasks left")
def schedule(async_fn, *args, **kwargs):
n = str(args[0])
print("scheduled " + n)
task = asyncio.create_task(async_fn(*args, **kwargs))
task.add_done_callback(lambda t: on_done(t, n))
running_tasks.add(task)
def fnf(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
schedule(fn, *args, **kwargs)
return wrapper
# main.py
# from fnf import fnf
@fnf
async def task(n):
print(f"{n} begins")
if n % 2:
await asyncio.sleep(n * 0.1)
print(f"{n} ends")
return
await asyncio.sleep(n * 0.01)
raise Exception("Ruh-roh " + str(n))
async def main():
[task(n) for n in range(10)]
await asyncio.sleep(2)
print("done")
if __name__ == "__main__":
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment