Debian Codegraph @

cylc/flow/timer.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 """Simple timer class."""
18
19 from time import time as now
20 from cylc.flow import LOG
21 from cylc.flow.wallclock import (
22 get_seconds_as_interval_string as get_interval_str
23 )
24
25 from typing import Callable, Optional
26
27
28 class Timer:
29 """Simple timer class for workflow timers."""
30
31 def __init__(
32 self, name: str, interval: float,
33 log_reset_func: Optional[Callable] = None
34 ) -> None:
35 """Initialize a timer."""
36 if log_reset_func is not None:
37 self.log_timer_reset = log_reset_func
38 else:
39 self.log_timer_reset = LOG.warning
40 self.name = name.replace('timeout', 'timer')
41 self.interval = get_interval_str(interval)
42 self.interval_float = interval
43 self.timeout: Optional[float] = None
44
45 def reset(self) -> None:
46 """Start the timer now (by setting a concrete timeout value)."""
47 self.timeout = now() + self.interval_float
48 self.log_timer_reset(f"{self.interval} {self.name} starts NOW")
49
50 def stop(self) -> None:
51 """Stop the timer."""
52 if self.timeout is None:
53 return
54 self.timeout = None
55 LOG.info(f"{self.name} stopped")
56
57 def timed_out(self) -> bool:
58 """Return whether timed out yet."""
59 if self.timeout is not None and now() > self.timeout:
60 LOG.warning(f"{self.name} timed out after {self.interval}")
61 self.timeout = None
62 return True
63 else:
64 return False