Skip to content

Permanently running background tasks #6992

Answered by insomnes
tweakimp asked this question in Questions
Discussion options

You must be logged in to vote

@tweakimp hello!
Maybe you can use on startup event functionality:
https://fastapi.tiangolo.com/advanced/events/

But don't add your main function directly, cause it will run forever.
Maybe you can do it with starting daemon thread of main() in some startup function.

If you consider using of asyncio (and understand async as general concept) you can try something like this:

class BackgroundRunner:
    def __init__(self):
        self.value = 0

    async def run_main(self):
        while True:
            await asyncio.sleep(0.1)
            self.value += 1

runner = BackgroundRunner()

@app.on_event('startup')
async def app_startup():
    asyncio.create_task(runner.run_main())


@app.get("…

Replies: 12 comments 4 replies

Comment options

You must be logged in to vote
3 replies
@Raphencoder
Comment options

@Trolldemorted
Comment options

@ahmedhr
Comment options

Answer selected by Kludex
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@kurkurzz
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question or problem question-migrate
Converted from issue

This discussion was converted from issue #2713 on February 27, 2023 23:36.