Skip to content

Permanently running background tasks #2713

@tweakimp

Description

@tweakimp

How can I add permanently running background tasks?

I want to have the following behaviour:

  • Start the api and main starts to run as well.
  • Open the browser and call the endpoint /.
  • It returns the current value of value.

Example

import time

import uvicorn
from fastapi import FastAPI

app = FastAPI()


def main():
    # where and how should i start this function
    value = 0
    while True:
        time.sleep(0.1)
        value += 1


@app.get("/")
def root():
    # how can i read value from main?
    return value


if __name__ == "__main__":
    uvicorn.run("api:app", host="0.0.0.0", port=8001, reload=True)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions