Commits

Alexander Shorin  committed ab35cff

Add loop decorator for main function.

  • Participants
  • Parent commits 8d7134d

Comments (0)

Files changed (1)

File hydra/daemons.py

 import os
 import logging
 import logging.config
+import time
 import sys
 from copy import deepcopy
 from couchdb import ResourceNotFound
 
 
 DEFAULT_CONFIG = {
-    'app': {},
+    'app': {
+        'loop_timeout': 10,
+    },
     'couchdb': {
         'main': {
             'dbs': {},
                 config['handlers'].pop(name)
         logging.config.dictConfig(config)
 
+    def loop(self, *fatal_errors):
+        def decorator(func):
+            @self.main
+            def main():
+                while True:
+                    try:
+                        if self.config.reload():
+                            self.setup()
+                        func()
+                    except KeyboardInterrupt:
+                        self.log.warn('Terminating')
+                        break
+                    except Exception as err:
+                        self.log.exception('Something went wrong')
+                        if isinstance(err, fatal_errors):
+                            self.log.warn('Terminating')
+                            break
+                    timeout = self.config['app']['loop_timeout']
+                    self.log.debug('Resuming in %s sec.' % timeout)
+                    time.sleep(timeout)
+            main.__name__ = func.__name__
+            main.__doc__ = func.__doc__
+            return main
+        return decorator
+
     def main(self, func):
         self.main_func = func
+        return func
 
     def run(self):
         self.setup()