Skip to content

Instantly share code, notes, and snippets.

@Itz-fork
Created August 7, 2022 08:16
Show Gist options
  • Save Itz-fork/927280185727af419fe37c95c10f8924 to your computer and use it in GitHub Desktop.
Save Itz-fork/927280185727af419fe37c95c10f8924 to your computer and use it in GitHub Desktop.
Run async function in the background using asyncio and multiprocessing
from asyncio import sleep, get_event_loop, get_running_loop
from multiprocessing import Process
# Simple callback function
async def my_callback_func():
print(f"Doing something in the background!")
await sleep(1)
# Run the callback function in a loop as you need to use async / await
# Else you can just ignore this function and call your callback function directly from "fire_callback" function
def handle_callback(callback):
try:
loop = get_running_loop()
except:
loop = get_event_loop()
loop.run_until_complete(callback())
# Fire the callback function
def fire_callback(callback):
Process(target=handle_callback, args=(callback,)).start()
# Call "fire_callback" for a test run
fire_callback(my_callback_func)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment