Skip to content

[QUESTION] Stop bot with infinite background job/task gracefully #3181

@max-dw-i

Description

@max-dw-i

Issue I am facing

I have a bot with an infinite background job. What is the best, "canonical" way of stopping/quitting the bot in this case (with saving the state to a persistent storage and other stuff that Application.stop() does). Ideally, it should work not only when I press ctrl-c but in any scenario when the bot stops (for example, when an exception that could not be handled for some reason was raised and the bot stopped).
So If I press ctrl-c, the bot does not stop. I need to press ctrl-c one more time and the process does not finish properly (e.g. 'before stop' persistence does not work).

Traceback to the issue

No response

Related part of your code

class Bot:
    def init(self, app: Application) -> None:
        self.app = app
        self.app.job_queue.run_once(
            callback=self.infinite_task,
            when=0
        )

    async def infinite_task(self) -> None:
        while True:
            print("I'm a bot")
            await asyncio.sleep(1)

application = ApplicationBuilder().token('TOKEN').build()
Bot(application)
application.run_polling()

Operating System

Debian 10

Version of Python, python-telegram-bot & dependencies

python-telegram-bot 20.0a2
Bot API 6.1
Python 3.7.3 (default, Jan 22 2021, 20:04:44)  [GCC 8.3.0]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Priority

    None yet

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions