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 |
Allen Li | 26d1008 | 2016-12-16 16:31:02 -0800 | [diff] [blame] | 28 | |
| 29 | def loop_once(self): |
| 30 | """Do actions for a single loop.""" |
| 31 | try: |
Allen Li | 38de641 | 2016-12-16 16:52:45 -0800 | [diff] [blame] | 32 | self._callback() |
Allen Li | 26d1008 | 2016-12-16 16:31:02 -0800 | [diff] [blame] | 33 | except Exception: |
| 34 | logger.exception('Error during loop.') |
| 35 | |
| 36 | def loop_forever(self): |
| 37 | while True: |
| 38 | self.loop_once() |
| 39 | _force_sleep(self._interval) |
Allen Li | 26d1008 | 2016-12-16 16:31:02 -0800 | [diff] [blame] | 40 | |
| 41 | |
| 42 | def _force_sleep(secs): |
| 43 | """Force sleep for at least the given number of seconds.""" |
| 44 | now = time.time() |
| 45 | finished_time = now + secs |
| 46 | while now < finished_time: |
| 47 | remaining = finished_time - now |
| 48 | logger.debug('Sleeping for %d, %d remaining', secs, remaining) |
| 49 | time.sleep(remaining) |
| 50 | now = time.time() |