Revision 557838c1 lib/utils.py
b/lib/utils.py | ||
---|---|---|
3909 | 3909 |
|
3910 | 3910 |
""" |
3911 | 3911 |
return [val for val in items if not self.Matches(val)] |
3912 |
|
|
3913 |
|
|
3914 |
class RunningTimeout(object): |
|
3915 |
"""Class to calculate remaining timeout when doing several operations. |
|
3916 |
|
|
3917 |
""" |
|
3918 |
__slots__ = [ |
|
3919 |
"_allow_negative", |
|
3920 |
"_start_time", |
|
3921 |
"_time_fn", |
|
3922 |
"_timeout", |
|
3923 |
] |
|
3924 |
|
|
3925 |
def __init__(self, timeout, allow_negative, _time_fn=time.time): |
|
3926 |
"""Initializes this class. |
|
3927 |
|
|
3928 |
@type timeout: float |
|
3929 |
@param timeout: Timeout duration |
|
3930 |
@type allow_negative: bool |
|
3931 |
@param allow_negative: Whether to return values below zero |
|
3932 |
@param _time_fn: Time function for unittests |
|
3933 |
|
|
3934 |
""" |
|
3935 |
object.__init__(self) |
|
3936 |
|
|
3937 |
if timeout is not None and timeout < 0.0: |
|
3938 |
raise ValueError("Timeout must not be negative") |
|
3939 |
|
|
3940 |
self._timeout = timeout |
|
3941 |
self._allow_negative = allow_negative |
|
3942 |
self._time_fn = _time_fn |
|
3943 |
|
|
3944 |
self._start_time = None |
|
3945 |
|
|
3946 |
def Remaining(self): |
|
3947 |
"""Returns the remaining timeout. |
|
3948 |
|
|
3949 |
""" |
|
3950 |
if self._timeout is None: |
|
3951 |
return None |
|
3952 |
|
|
3953 |
# Get start time on first calculation |
|
3954 |
if self._start_time is None: |
|
3955 |
self._start_time = self._time_fn() |
|
3956 |
|
|
3957 |
# Calculate remaining time |
|
3958 |
remaining_timeout = self._start_time + self._timeout - self._time_fn() |
|
3959 |
|
|
3960 |
if not self._allow_negative: |
|
3961 |
# Ensure timeout is always >= 0 |
|
3962 |
return max(0.0, remaining_timeout) |
|
3963 |
|
|
3964 |
return remaining_timeout |
Also available in: Unified diff