Allen Li | 26d1008 | 2016-12-16 16:31:02 -0800 | [diff] [blame] | 1 | # Copyright 2016 The Chromium OS Authors. All rights reserved. |
| 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
| 4 | |
| 5 | """Sleep loop.""" |
| 6 | |
| 7 | from __future__ import print_function |
| 8 | |
| 9 | import time |
| 10 | |
| 11 | from chromite.lib import cros_logging as logging |
| 12 | |
| 13 | logger = logging.getLogger(__name__) |
| 14 | |
| 15 | |
| 16 | class SleepLoop(object): |
| 17 | """Sleep loop.""" |
| 18 | |
| 19 | def __init__(self, callback, interval=60): |
| 20 | """Initialize instance. |
| 21 | |
| 22 | Args: |
| 23 | callback: Function to call on each loop. |
| 24 | interval: Time between loops in seconds. |
| 25 | """ |
| 26 | self._callback = callback |
| 27 | self._interval = interval |
| 28 | self._cycles = 0 |
| 29 | |
| 30 | def loop_once(self): |
| 31 | """Do actions for a single loop.""" |
| 32 | try: |
| 33 | self._callback(self._cycles) |
| 34 | except Exception: |
| 35 | logger.exception('Error during loop.') |
| 36 | |
| 37 | def loop_forever(self): |
| 38 | while True: |
| 39 | self.loop_once() |
| 40 | _force_sleep(self._interval) |
| 41 | self._cycles = (self._cycles + 1) % 60 |
| 42 | |
| 43 | |
| 44 | def _force_sleep(secs): |
| 45 | """Force sleep for at least the given number of seconds.""" |
| 46 | now = time.time() |
| 47 | finished_time = now + secs |
| 48 | while now < finished_time: |
| 49 | remaining = finished_time - now |
| 50 | logger.debug('Sleeping for %d, %d remaining', secs, remaining) |
| 51 | time.sleep(remaining) |
| 52 | now = time.time() |