| 1 |
Exception Handling |
| 2 |
################## |
| 3 |
|
| 4 |
Schedule doesn't catch exceptions that happen during job execution. Therefore any exceptions thrown during job execution will bubble up and interrupt schedule's run_xyz function. |
| 5 |
|
| 6 |
If you want to guard against exceptions you can wrap your job function |
| 7 |
in a decorator like this: |
| 8 |
|
| 9 |
.. code-block:: python |
| 10 |
|
| 11 |
import functools |
| 12 |
|
| 13 |
def catch_exceptions(cancel_on_failure=False): |
| 14 |
def catch_exceptions_decorator(job_func): |
| 15 |
@functools.wraps(job_func) |
| 16 |
def wrapper(*args, **kwargs): |
| 17 |
try: |
| 18 |
return job_func(*args, **kwargs) |
| 19 |
except: |
| 20 |
import traceback |
| 21 |
print(traceback.format_exc()) |
| 22 |
if cancel_on_failure: |
| 23 |
return schedule.CancelJob |
| 24 |
return wrapper |
| 25 |
return catch_exceptions_decorator |
| 26 |
|
| 27 |
@catch_exceptions(cancel_on_failure=True) |
| 28 |
def bad_task(): |
| 29 |
return 1 / 0 |
| 30 |
|
| 31 |
schedule.every(5).minutes.do(bad_task) |
| 32 |
|
| 33 |
Another option would be to subclass Schedule like @mplewis did in `this example <https://gist.github.com/mplewis/8483f1c24f2d6259aef6>`_. |