0

I am trying to use AsyncIOScheduler and CronTrigger to run an async function at a given time.


import asyncio
from datetime import timedelta,datetime
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from time import sleep

async def pastTime(endTime):
    while(datetime.now()<=endTime):
        print(datetime.now());
        print(endTime);
        sleep(1);
        
async def dummyJob():# The real one needs to call into asyncIO
    print("scheduled job running at");
    print(datetime.now());
    
def entranceFcn():
    trigger = CronTrigger(day_of_week='mon-fri', hour= '9-23', minute="*");
    sched = AsyncIOScheduler();
    sched.add_job(dummyJob, trigger, misfire_grace_time=None);
    sched.start();
    TODAY_16_00_TIME = datetime.now().replace(hour=22,minute=20,second=0,microsecond=0);
    endTime = TODAY_16_00_TIME + timedelta(seconds = 60);
    try:
       #asyncio.get_event_loop().run_until_complete(pastTime(endTime));
       asyncio.get_event_loop().run_forever();#   => this works!
    except KeyboardInterrupt:
       sched.shutdown()

entranceFcn();

The code above works as expected and is able to run dummyJob at trigger times. However, when I tried to add some conditions to the end event loop using:

asyncio.get_event_loop().run_until_complete(pastTime(endTime))

The dummyJob() is no longer scheduled and run (nothing is printed out). I tried different misfire_grace_time and it still doesn't work.

My guess is the pastTime function is somehow preventing the launching of a separate thread/coroutine.

Is this expected and can someone help with this? I need to stop get_event_loop() with some condition and then switch to a different cron job later once the condition is not satisfied.

Thank you very much.

Aqib Chattha
  • 197
  • 11
knightyangpku
  • 75
  • 1
  • 4

0 Answers0