From cfda7c79b0497420ac1008291f7e600bf45b9289 Mon Sep 17 00:00:00 2001 From: Laurent Peuch Date: Mon, 10 Sep 2018 03:29:40 +0200 Subject: [PATCH] [enh] add decorator to always relaunch a function --- schedule.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 schedule.py diff --git a/schedule.py b/schedule.py new file mode 100644 index 0000000..b71b21e --- /dev/null +++ b/schedule.py @@ -0,0 +1,21 @@ +import asyncio +from functools import wraps + + +def always_relaunch(sleep): + def decorator(function): + @wraps(function) + async def wrap(*args, **kwargs): + while True: + try: + await function(*args, **kwargs) + except KeyboardInterrupt: + return + except Exception as e: + import traceback + traceback.print_exc() + print(f"Error: exception in function '{function.__name__}', relaunch in {sleep} seconds") + finally: + await asyncio.sleep(sleep) + return wrap + return decorator