Refactor code layout
[pti/o2.git] / o2common / service / watcher / worker.py
diff --git a/o2common/service/watcher/worker.py b/o2common/service/watcher/worker.py
new file mode 100644 (file)
index 0000000..64d189d
--- /dev/null
@@ -0,0 +1,61 @@
+# Copyright (C) 2021 Wind River Systems, Inc.\r
+#\r
+#  Licensed under the Apache License, Version 2.0 (the "License");\r
+#  you may not use this file except in compliance with the License.\r
+#  You may obtain a copy of the License at\r
+#\r
+#      http://www.apache.org/licenses/LICENSE-2.0\r
+#\r
+#  Unless required by applicable law or agreed to in writing, software\r
+#  distributed under the License is distributed on an "AS IS" BASIS,\r
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+#  See the License for the specific language governing permissions and\r
+#  limitations under the License.\r
+\r
+import time\r
+import sched\r
+from o2common.service.watcher.base import WatcherTree\r
+\r
+from o2common.helper import o2logging\r
+logger = o2logging.get_logger(__name__)\r
+\r
+\r
+class PollWorker(object):\r
+    def __init__(self, interval=10) -> None:\r
+        super().__init__()\r
+        self.watchers = []\r
+        self.schedinstance = sched.scheduler(time.time, time.sleep)\r
+        self.schedinterval = interval\r
+        self._stopped = True\r
+\r
+    def set_interval(self, interval):\r
+        if interval > 0:\r
+            self.schedinterval = interval\r
+        else:\r
+            raise Exception("Invalid interval:" + interval)\r
+\r
+    def add_watcher(self, watcher: WatcherTree):\r
+        self.watchers.append(watcher)\r
+\r
+    def _repeat(self):\r
+        logger.debug("_repeat started")\r
+        if self._stopped:\r
+            return\r
+        for w in self.watchers:\r
+            try:\r
+                # logger.debug("about to probe:"+w)\r
+                w.probe(None)\r
+            except Exception as ex:\r
+                logger.warning("Worker raises exception:" + str(ex))\r
+                continue\r
+        self.schedinstance.enter(self.schedinterval, 1, self._repeat)\r
+\r
+    # note the sched run will block current thread\r
+    def start(self):\r
+        self._stopped = False\r
+        logger.debug('about to start sched task')\r
+        self.schedinstance.enter(self.schedinterval, 1, self._repeat)\r
+        self.schedinstance.run()\r
+\r
+    def stop(self):\r
+        self._stopped = True\r