OLD | NEW |
(Empty) | |
| 1 # Copyright 2017 The Chromium 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 import threading |
| 6 import time |
| 7 |
| 8 class RepeatingTimer(object): |
| 9 """A simple repeating timer.""" |
| 10 |
| 11 def __init__(self, target, interval_s): |
| 12 """Create a timer object which will repeatedly run the target function |
| 13 with the specified interval. Interval should be specified in seconds. |
| 14 """ |
| 15 self._target = target |
| 16 self._interval = interval_s |
| 17 self._stop = threading.Event() |
| 18 self._stop.set() |
| 19 self._timer_thread = None |
| 20 |
| 21 def _BackgroundThread(self): |
| 22 target_time = time.time() + self._interval |
| 23 while not self._stop.wait(max(0, target_time - time.time())): |
| 24 target_time = target_time + self._interval |
| 25 self._target() |
| 26 |
| 27 def Start(self): |
| 28 """Start the timer. The target function will be called at regular intervals |
| 29 after the given interval elapses. The timer may be stopped and restarted. |
| 30 This must not be called if the timer is already running (Stop should be |
| 31 called to stop it first). |
| 32 """ |
| 33 # start new timer thread |
| 34 self._stop.clear() |
| 35 self._timer_thread = threading.Thread(target=self._BackgroundThread) |
| 36 self._timer_thread.start() |
| 37 |
| 38 def Stop(self): |
| 39 """Stop the timer and block until it has stopped. |
| 40 The timer must have been started before calling Stop.""" |
| 41 self._stop.set() |
| 42 self._timer_thread.join() |
| 43 |
| 44 def IsRunning(self): |
| 45 """Return true if the timer is currently running.""" |
| 46 return not self._stop.is_set() |
OLD | NEW |