Skip to content

Commit

Permalink
duration for the start() method
Browse files Browse the repository at this point in the history
  • Loading branch information
pomponchik committed Jul 23, 2024
1 parent d763b57 commit da3f29b
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions metronomes/metronome.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,7 @@ def __init__(self, iteration: Union[int, float], callback: Callable[[], Any], su
self.logger: LoggerProtocol = logger
self.token: AbstractToken = SimpleToken(token)
if duration is not None:
if duration < 0:
raise ValueError('The total duration of the metronome operation cannot be less than zero.')
elif iteration > duration:
raise ValueError('The time of one iteration cannot exceed the running time of the metronome as a whole.')
self.token = self.token + TimeoutToken(duration)
self.token += self.create_duration_token(duration)
self.thread: Optional[Thread] = None
self.started: bool = False
self.stopped: bool = False
Expand All @@ -52,13 +48,16 @@ def __exit__(self, exception_type: Optional[Type[BaseException]], exception_valu
self.stop()
return False

def start(self, token: AbstractToken = DefaultToken()) -> 'Metronome':
def start(self, token: AbstractToken = DefaultToken(), duration: Optional[Union[int, float]] = None) -> 'Metronome':
with self.lock:
if self.stopped:
raise RunStoppedMetronomeError('Metronomes are disposable, you cannot restart a stopped metronome.')
if self.started:
raise RunAlreadyStartedMetronomeError('The metronome has already been launched.')

if duration is not None:
token += self.create_duration_token(duration)

self.thread = Thread(target=self.run_loop, args=(self.token + token,))
self.thread.daemon = True

Expand Down Expand Up @@ -102,3 +101,11 @@ def run_loop(self, token: AbstractToken) -> None:
self.sleeping_callback(sleep_time)

self.stopped = True

def create_duration_token(self, duration: Union[int, float]) -> TimeoutToken:
if duration < 0:
raise ValueError('The total duration of the metronome operation cannot be less than zero.')
elif self.iteration > duration:
raise ValueError('The time of one iteration cannot exceed the running time of the metronome as a whole.')

return TimeoutToken(duration)

0 comments on commit da3f29b

Please sign in to comment.