Home > OS >  Sheduled function call doesn't work. How to fix it? Python, aiogram
Sheduled function call doesn't work. How to fix it? Python, aiogram

Time:08-21

I currently codding a telegram bot, and it needs to check the site for new transactions every minute. I am doing this by using this code:

async def check(wait_for):
    while True:
        logging.warning(1)
        await asyncio.sleep(wait_for)
        logging.warning(2)
        transactions = parsing()
        if transactions: ...

This is function I need to call (logging.warnings is some kind of debug)

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.create_task(check(60))
    start_webhook(...

And that's how i call it. But there's a problem: everything it does is logging 1 before the webhook has even started:

2022-08-20T22:48:17.444445 00:00 app[web.1]: WARNING:root:1
2022-08-20T22:48:17.554609 00:00 app[web.1]: WARNING:aiogram:Updates were skipped successfully.
2022-08-20T22:48:17.634728 00:00 app[web.1]: ======== Running on http://0.0.0.0:22044 ========
2022-08-20T22:48:17.634735 00:00 app[web.1]: (Press CTRL C to quit)...

Another worlds, everything after "await asyncio.sleep(wait_for)" in my function is never performed. Why?

CodePudding user response:

your check function should sleep before awaiting the sleep function, then while the check function is sleeping the webhook function will start.

async def check(wait_for):
    while True:
        await asyncio.sleep(wait_for)
        logging.warning(1)
        logging.warning(2)
        transactions = parsing()
        if transactions: ..

CodePudding user response:

It looks like you need to save a reference to the Task you just created(create_task returns a Task-object), to save it from being garbage collected, as the event_loop itself only stores a weak reference. Just create some global variable alltasks = set() at the start of the file and alltasks.add() all your tasks.

Info: you should probably gather your tasks together and schedule them to be run when asyncio.run() is called. I recommend reading the Documentation on asyncio Tasks and event loop if you are building a bigger project. https://docs.python.org/3/library/asyncio-eventloop.html#asyncio-event-loop

https://docs.python.org/3/library/asyncio.html

https://docs.python.org/3/library/asyncio-task.html

alltasks = set()

if __name__ == '__main__'
     loop = asyncio.get_event_loop()
     new_task = loop.create_task(check(60))
     alltasks.add(new_task)
    ...

  • Related