def start(self) -> float: """ Start the timer if it was not started or terminated previously. Raises ------ TimerError.AlreadyStartedTimerError If the timer was already started. TimerError.AlreadyTerminatedTimerError If the timer was already terminated. Returns ------- float Current internal time (in internal seconds). """ if self._started: raise TimerError.AlreadyStartedTimerError if self._terminated: raise TimerError.AlreadyTerminatedTimerError self._started = True self._last_time_update = time.perf_counter() self._internal_timer_task = Constants.create_fragile_task(self._internal_timer()) # print(f'[{time.time()}] Timer {self.get_id()} started at {self._base_value}.') self._check_structure() return self._base_value # This is the current internal time, as no seconds have passed.
def _refresh(self): """ Interrupt the current timestep with a cancellation order. If the steptimer is not currently running, this function does nothing. Returns ------- None. """ if not self._task: return self._due_continue_timestep_progress = True Constants.create_fragile_task(self._cancel_and_await(self._task))
def _continue_timestep(self): if self._was_terminated: # This code should only run if it takes longer for the timer to be terminated than # the firing interval. return if self._timer_value <= self._min_timer_value: self._timer_value = self._min_timer_value if self._timestep_length < 0: self._was_terminated = True self._on_min_end() return elif self._timer_value >= self._max_timer_value: self._timer_value = self._max_timer_value if self._timestep_length > 0: self._was_terminated = True self._on_max_end() return # This moment represents the instant a timestep resumes from pausing/refreshing # or the very beginning of one. self._just_paused = False self._just_unpaused = False # If the timer is paused, wait _firing_interval seconds again if self._is_paused: return # Else, if a timestep just finished without any interruptions # Reset time spent in timestep and last update to timestep if not self._due_continue_timestep_progress: self._reset_subtimestep_elapsed() self._on_timestep_end() adapted_interval = self._firing_interval-self._time_spent_in_timestep if adapted_interval < 0: adapted_interval = 0 self._due_continue_timestep_progress = False self._task = Constants.create_fragile_task(self._wait_timestep_end(adapted_interval))
def create_task(self, client, args): """ Create a new task for given client with given arguments. Parameters ---------- client: ClientManager.Client Client associated to the task. args: list Arguments of the task. """ # Abort old task if it exists try: old_task = self.get_task(client, args) if not old_task.done() and not old_task.cancelled(): self.cancel_task(old_task) except KeyError: pass async_function = getattr(self, args[0])(client, args[1:]) async_future = Constants.create_fragile_task(async_function) self.client_tasks[client.id][args[0]] = (async_future, args[1:], dict())