Mike Frysinger | f1ba7ad | 2022-09-12 05:42:57 -0400 | [diff] [blame] | 1 | # Copyright 2016 The ChromiumOS Authors |
Allen Li | 26d1008 | 2016-12-16 16:31:02 -0800 | [diff] [blame] | 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 | |
Allen Li | 13bdf0c | 2017-03-02 15:18:16 -0800 | [diff] [blame] | 7 | from __future__ import absolute_import |
Allen Li | 26d1008 | 2016-12-16 16:31:02 -0800 | [diff] [blame] | 8 | |
Chris McDonald | 59650c3 | 2021-07-20 15:29:28 -0600 | [diff] [blame] | 9 | import logging |
Allen Li | 26d1008 | 2016-12-16 16:31:02 -0800 | [diff] [blame] | 10 | import time |
| 11 | |
Allen Li | 26d1008 | 2016-12-16 16:31:02 -0800 | [diff] [blame] | 12 | |
| 13 | logger = logging.getLogger(__name__) |
| 14 | |
| 15 | |
| 16 | class SleepLoop(object): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 17 | """Sleep loop.""" |
Allen Li | 26d1008 | 2016-12-16 16:31:02 -0800 | [diff] [blame] | 18 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 19 | def __init__(self, callback, interval=60): |
| 20 | """Initialize instance. |
Allen Li | 26d1008 | 2016-12-16 16:31:02 -0800 | [diff] [blame] | 21 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 22 | Args: |
Trent Apted | 66736d8 | 2023-05-25 10:38:28 +1000 | [diff] [blame] | 23 | callback: Function to call on each loop. |
| 24 | interval: Time between loops in seconds. |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 25 | """ |
| 26 | self._callback = callback |
| 27 | self._interval = interval |
Allen Li | 26d1008 | 2016-12-16 16:31:02 -0800 | [diff] [blame] | 28 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 29 | def loop_once(self): |
| 30 | """Do actions for a single loop.""" |
| 31 | try: |
| 32 | self._callback() |
| 33 | except Exception: |
| 34 | logger.exception("Error during loop.") |
Allen Li | 26d1008 | 2016-12-16 16:31:02 -0800 | [diff] [blame] | 35 | |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 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): |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 43 | """Force sleep for at least the given number of seconds.""" |
Allen Li | 26d1008 | 2016-12-16 16:31:02 -0800 | [diff] [blame] | 44 | now = time.time() |
Alex Klein | 1699fab | 2022-09-08 08:46:06 -0600 | [diff] [blame] | 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() |