Last active
May 3, 2024 14:30
-
-
Save globus243/662ffe8343e893125a999a53a33eeedb to your computer and use it in GitHub Desktop.
Python setInterval() equivalent
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 | |
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" ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More details: https://blog.timhartmann.de/2024/05/01/python-setinterval/