1 # Copyright (C) 2021 Wind River Systems, Inc.
\r
3 # Licensed under the Apache License, Version 2.0 (the "License");
\r
4 # you may not use this file except in compliance with the License.
\r
5 # You may obtain a copy of the License at
\r
7 # http://www.apache.org/licenses/LICENSE-2.0
\r
9 # Unless required by applicable law or agreed to in writing, software
\r
10 # distributed under the License is distributed on an "AS IS" BASIS,
\r
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
12 # See the License for the specific language governing permissions and
\r
13 # limitations under the License.
\r
17 # from o2common.service.unit_of_work import AbstractUnitOfWork
\r
18 from o2common.service.watcher.base import WatcherTree
\r
20 from o2common.helper import o2logging
\r
21 logger = o2logging.get_logger(__name__)
\r
24 class PollWorker(object):
\r
25 def __init__(self, interval=10, bus=None) -> None:
\r
28 self.schedinstance = sched.scheduler(time.time, time.sleep)
\r
29 self.schedinterval = interval
\r
30 self._stopped = True
\r
33 def set_interval(self, interval):
\r
35 self.schedinterval = interval
\r
37 raise Exception("Invalid interval:" + interval)
\r
39 def add_watcher(self, watcher: WatcherTree):
\r
40 self.watchers.append(watcher)
\r
43 logger.debug("_repeat started")
\r
46 for w in self.watchers:
\r
48 # logger.debug("about to probe:"+w)
\r
50 except Exception as ex:
\r
51 logger.warning("Worker raises exception:" + str(ex))
\r
55 if self._bus is not None:
\r
56 events = self._bus.uow.collect_new_events()
\r
57 for event in events:
\r
58 self._bus.handle(event)
\r
60 self.schedinstance.enter(self.schedinterval, 1, self._repeat)
\r
62 # note the sched run will block current thread
\r
64 self._stopped = False
\r
65 logger.debug('about to start sched task')
\r
66 self.schedinstance.enter(self.schedinterval, 1, self._repeat)
\r
67 self.schedinstance.run()
\r
70 self._stopped = True
\r