Skip to content

Instantly share code, notes, and snippets.

@globus243
Last active May 3, 2024 14:30
Show Gist options
  • Save globus243/662ffe8343e893125a999a53a33eeedb to your computer and use it in GitHub Desktop.
Save globus243/662ffe8343e893125a999a53a33eeedb to your computer and use it in GitHub Desktop.
Python setInterval() equivalent
from threading import Timer
class SetInterval:
def __init__( self, func, sec, run_now = False, args = None, kwargs = None ):
self.func = func
self.sec = sec
self.args = args
self.kwargs = kwargs
self.thread = None
self.start( run_now )
def start( self, run_now = False ):
args = [ ] if self.args is None else self.args
kwargs = { } if self.kwargs is None else self.kwargs
def func_wrapper( _args = None, _kwargs = None ):
_args = [ ] if _args is None else _args
_kwargs = { } if _kwargs is None else _kwargs
self.func( *_args, **_kwargs )
self.start( )
if run_now:
self.func( *args, **kwargs )
self.thread = Timer(
self.sec, func_wrapper, kwargs = {
"_args": args,
"_kwargs": kwargs
} )
self.thread.start( )
def cancel( self ):
if self.thread is not None:
self.thread.cancel( )
self.thread = None
if __name__ == "__main__":
import time
def print_hello( ):
print( "hello" )
interval = SetInterval( print_hello, 1, True )
time.sleep( 5 )
# prints hello 5 times
interval.cancel( )
print( "interval canceled" )
@globus243
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment