'How to pause a function and resume it later in Python?

I have a async function that sends message to a large list of users. (this takes a long time) I need to be able to pause this function and resume it when I want. I'm currently using it like this but there will be a lots of request to the database.

async def func():
    users = ...  # request to database to get the list of users
    for user in users:
        status = str  # request to database to check the status

        if status == 'pause':
            while True:
                status = str  # request to database to check the status
                if status == 'work':
                    break

        elif status == 'work':
            await send_message(user)

        elif status == 'stop':
            break      

There should be a better way to do it.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source