I was trying to figure out how to make a setInterval that cancels in python without making an entire new class to do that, I figured out how but now I'm wondering if there is a better way to do it.
The code below seems to work fine, but I have not thoroughly tested it.
import threading
def setInterval(func, sec):
def inner():
while function.isAlive():
func()
time.sleep(sec)
function = type("setInterval", (), {}) # not really a function I guess
function.isAlive = lambda: function.vars["isAlive"]
function.vars = {"isAlive": True}
function.cancel = lambda: function.vars.update({"isAlive": False})
thread = threading.Timer(sec, inner)
thread.setDaemon(True)
thread.start()
return function
interval = setInterval(lambda: print("Hello, World"), 60) # will print Hello, World every 60 seconds
# 3 minutes later
interval.cancel() # it will stop printing Hello, World
Is there a way to do the above without making a dedicated class that inherits from threading.Thread
or using the type("setInterval", (), {})
? Or am I stuck in deciding between making a dedicated class or continue to use type