Last active
June 4, 2019 13:56
-
-
Save derkzomer/60b509820e5983f0739727806f3425fa to your computer and use it in GitHub Desktop.
Python repeat timer
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 RepeatedTimer(object): | |
def __init__(self, interval, function, *args, **kwargs): | |
self._timer = None | |
self.function = function | |
self.interval = interval | |
self.args = args | |
self.kwargs = kwargs | |
self.is_running = False | |
self.start() | |
def _run(self): | |
self.is_running = False | |
self.start() | |
self.function(*self.args, **self.kwargs) | |
def start(self): | |
if not self.is_running: | |
self._timer = Timer(self.interval, self._run) | |
self._timer.start() | |
self.is_running = True | |
def stop(self): | |
self._timer.cancel() | |
self.is_running = False | |
print("starting...") | |
rt = RepeatedTimer(5, API().query_public, "Ticker", data={"pair":"ATOMXBT"}, timeout=None) | |
try: | |
time.sleep(11) # your long-running job goes here... | |
finally: | |
rt.stop() # better in a try/finally block to make sure the program ends! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment