简体   繁体   中英

How to handle exceptions when using APScheduler?

I've just tried to use apsheduler(3.7.0) in Python3.7. I used a 'try/except' clause to handle exceptions in the job, but no exceptions got caught. The code is copied from official examples(which may be a little bit out of date I think)

from apscheduler.schedulers.blocking import BlockingScheduler

def test():
    print('test')
    raise SystemExit

if __name__ == "__main__":
    scheduler = BlockingScheduler()
    scheduler.add_executor('threadpool')
    scheduler.add_job(test, 'interval', seconds=5)
    try:
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        print('caught')

The scheduler kept running and the 'caught' never got printed, until I pressed ctrl+C . I also tried raising some other kind of exceptions(even KeyboardInterrupt ), it's still the same.

So did I do it wrong? How should I handle exceptions in the jobs?

You can be notified if a job raises an exception by means of an event listener:

from apscheduler.events import EVENT_JOB_ERROR

def listener(event):
    print(f'Job {event.job_id} raised {event.exception.__class__.__name__}')

scheduler.add_listener(listener, EVENT_JOB_ERROR)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM