Hency Chine
Hency Chine

Reputation: 33

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?

Upvotes: 3

Views: 3999

Answers (1)

Alex Grönholm
Alex Grönholm

Reputation: 5901

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)

Upvotes: 3

Related Questions