skip to Main Content

I’m developing a small web service with Flask which needs to run background tasks, preferably from a task queue. However, after googling the subject the only results were essentially Celery and Redis Queue, which apparently require separate queuing services and thus are options that are far too heavy and convoluted to deploy. As all I’m looking for is a simple background task queue that enables tasks to be queued and executed on separate threads/processes, does anyone know if there is anything like this available in Python?

3

Answers


  1. The asyncio library might be what you are looking for

    import asyncio
    
    async def main():
        print('Hello ...')
        await asyncio.sleep(1)
        print('... World!')
    
    # Python 3.7+
    asyncio.run(main())
    
    Login or Signup to reply.
  2. import threading
    import time
    
    class BackgroundTasks(threading.Thread):
        def run(self,*args,**kwargs):
            while True:
                print('Hello')
                time.sleep(1)
    
    t = BackgroundTasks()
    t.start()
    

    After the while statement , you can put the code you want to run in background. Maybe deleting some models , sending email or whatever.

    Login or Signup to reply.
  3. If you are using FastAPI, there is already implementation of BackgroundTasks

    You don’t need to implement Threading and Queues for doing background tasks after receiving the request.

    Code Implementation:

    from fastapi import BackgroundTasks, FastAPI
    
    app = FastAPI()
    
    # function that will run in background after sending the response
    def write_notification(email: str, message=""):
        with open("log.txt", mode="w") as email_file:
            content = f"notification for {email}: {message}"
            email_file.write(content)
    
    
    @app.post("/send-notification/{email}")
    async def send_notification(email: str, background_tasks: BackgroundTasks):
        background_tasks.add_task(write_notification, email, message="some notification")
        return {"message": "Tasks are happening in background"}
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search