Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

609
Views
Running separate infinite background thread in a python webapp (fastapi/flask/django)

How can i launch an application which does below 2 things:

  1. Expose rest endpoint via FastAPI.
  2. Run a seperate thread infintely (rabbitmq consumer - pika) waiting for request.

Below is the code through which i am launching the fastAPI server. But when i try to run a thread, before execution of below line, it says coroutine was never awaited.

enter image description here

How can both be run parallely?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Maybe this is not the answer you are looking for. There is a library called celery that makes multithreading easy to manage in python.

Check it out: https://docs.celeryproject.org/en/stable/getting-started/introduction.html

over 4 years ago · Santiago Trujillo Report

0

import asyncio
from concurrent.futures import ThreadPoolExecutor
from fastapi import FastAPI
import uvicorn

app = FastAPI()


def run(corofn, *args):
    loop = asyncio.new_event_loop()
    try:
        coro = corofn(*args)
        asyncio.set_event_loop(loop)
        return loop.run_until_complete(coro)
    finally:
        loop.close()


async def sleep_forever():
    await asyncio.sleep(1000)


#
async def main():
    loop = asyncio.get_event_loop()
    executor = ThreadPoolExecutor(max_workers=2)
    futures = [loop.run_in_executor(executor, run, sleep_forever),
               loop.run_in_executor(executor, run, uvicorn.run, app)]
    print(await asyncio.gather(*futures))


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

Note: This may hinder your FastAPI performance. Better approach would be to use a Celery Task

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!