Friday, 7 January 2022

How to use AsyncIOScheduler to run function from another function?

I'm having difficulty to understand how the AsyncIOScheduler works and how I can schedule a function inside the main function, or how is the proper way to do that.

How can I run the function foo every 10 seconds?

Suppose I have this structure:

package/
    controllers.py
    main.py

From the file controllers.py I've got a function called foo and the function is something like this:

async def foo():
    print('Hello World')

I'd like to run the function foo (and many others) from the file main.py, and this file is like:

import asyncio
from controllers import foo, bar
from apscheduler.schedulers.asyncio import AsyncIOScheduler

async def main():

    # Init message
    print('\nPress Ctrl-C to quit at anytime!\n' )
    
    await asyncio.create_task(bar())

    scheduler = AsyncIOScheduler()
    scheduler.add_job(await asyncio.create_task(foo()), "interval", seconds=10)
    scheduler.start()

if __name__ == "__main__":
    while True:
        try:
            asyncio.run(main())
        except Exception as e:
            print("Exception: " + str(e))

Is it right to run the scheduler this way? Or the timer will be reseted every time the main function is running?

I tried the code below, the loop interval works, but the main function not.

import asyncio
from controllers import foo, bar
from apscheduler.schedulers.asyncio import AsyncIOScheduler

async def main():

    # Init message
    print('\nPress Ctrl-C to quit at anytime!\n' )
    
    await asyncio.create_task(bar())

if __name__ == "__main__":

    scheduler = AsyncIOScheduler()
    scheduler.add_job(foo, "interval", seconds=10)
    scheduler.start()

    while True:
        try:
            asyncio.get_event_loop().run_forever()
            asyncio.run(main())
        except Exception as e:
            print("Exception: " + str(e))

If I changed the order from:

            asyncio.get_event_loop().run_forever()
            asyncio.run(main())

to:

            asyncio.run(main())
            asyncio.get_event_loop().run_forever()

I get the error: There is no current event loop in thread 'MainThread'.

The loop works (scheduler only), but the main function is not running, how can I put those together in loop?



from How to use AsyncIOScheduler to run function from another function?

No comments:

Post a Comment