Created
July 8, 2021 19:51
-
-
Save emrahgunduz/3ed8a43202f9688cf155db6bca0b782c to your computer and use it in GitHub Desktop.
A timed, self running, stoppable class for Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from threading import Timer | |
from typing import ClassVar | |
from typing import Optional | |
class SelfRunner( object ): | |
_timeout: ClassVar[ float ] = 10.0 | |
_timer: Optional[ Timer ] = None | |
_end_called: bool = False | |
def __init__ ( self, timeout: float ): | |
self._timeout = timeout | |
def _run ( self ): | |
pass | |
def _on_timer ( self ): | |
# Stop if already ending | |
if self._end_called: return | |
self._run() | |
# Stop if already ending | |
if self._end_called: return | |
# Start a new timer | |
self._timer = Timer( self._timeout, self._on_timer ) | |
self._timer.start() | |
def start ( self, instant_fire: bool = False ): | |
if instant_fire: | |
self._on_timer() | |
if self._timer is not None: | |
self._timer.cancel() | |
self._timer = None | |
self._timer = Timer( self._timeout, self._on_timer ) | |
self._timer.start() | |
def stop ( self ): | |
self._end_called = True | |
if self._timer is not None: | |
self._timer.cancel() | |
self._timer = None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment