blob: 081eea8949c26e4c4f668045b7a61763a6469adb [file] [log] [blame]
Allen Li26d10082016-12-16 16:31:02 -08001# 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
Allen Li13bdf0c2017-03-02 15:18:16 -08007from __future__ import absolute_import
Allen Li26d10082016-12-16 16:31:02 -08008from __future__ import print_function
9
10import time
11
12from chromite.lib import cros_logging as logging
13
14logger = logging.getLogger(__name__)
15
16
17class SleepLoop(object):
18 """Sleep loop."""
19
20 def __init__(self, callback, interval=60):
21 """Initialize instance.
22
23 Args:
24 callback: Function to call on each loop.
25 interval: Time between loops in seconds.
26 """
27 self._callback = callback
28 self._interval = interval
Allen Li26d10082016-12-16 16:31:02 -080029
30 def loop_once(self):
31 """Do actions for a single loop."""
32 try:
Allen Li38de6412016-12-16 16:52:45 -080033 self._callback()
Allen Li26d10082016-12-16 16:31:02 -080034 except Exception:
Allen Li867d4582017-05-24 18:00:43 -070035 logger.exception(u'Error during loop.')
Allen Li26d10082016-12-16 16:31:02 -080036
37 def loop_forever(self):
38 while True:
39 self.loop_once()
40 _force_sleep(self._interval)
Allen Li26d10082016-12-16 16:31:02 -080041
42
43def _force_sleep(secs):
44 """Force sleep for at least the given number of seconds."""
45 now = time.time()
46 finished_time = now + secs
47 while now < finished_time:
48 remaining = finished_time - now
Allen Li867d4582017-05-24 18:00:43 -070049 logger.debug(u'Sleeping for %d, %d remaining', secs, remaining)
Allen Li26d10082016-12-16 16:31:02 -080050 time.sleep(remaining)
51 now = time.time()