[Django]-I want to keep a long process running in the background in django

3👍

AsyncIO event loops are not thread safe; you can’t run the loop from a different thread than it was originally created on. Your run_loop function should instead take no arguments, and create/start a new event loop to run your coroutine:

LOOP = None

def run_loop():
    global LOOP
    LOOP = asyncio.new_event_loop()
    LOOP.run_until_complete(long_running_task())

threading.Thread(target=run_loop).start()

# <do other things>

LOOP.call_soon_threadsafe(LOOP.stop)

Leave a comment