Skip to content

Instantly share code, notes, and snippets.

@emrahgunduz
Created July 8, 2021 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emrahgunduz/3ed8a43202f9688cf155db6bca0b782c to your computer and use it in GitHub Desktop.
Save emrahgunduz/3ed8a43202f9688cf155db6bca0b782c to your computer and use it in GitHub Desktop.
A timed, self running, stoppable class for Python
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