Created
June 8, 2017 05:39
-
-
Save say4n/f8780ec0e16afe1b88952d3185c1053c to your computer and use it in GitHub Desktop.
Reapeat a python function after a set interval, non blocking code !
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
import threading | |
import time | |
class RepeatedTimer(object): | |
def __init__(self, interval, _function, *args, **kwargs): | |
self._timer = None | |
self.interval = interval | |
self.function = _function | |
self.args = args | |
self.kwargs = kwargs | |
self.is_running = False | |
self.next_call = time.time() | |
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.next_call += self.interval | |
self._timer = threading.Timer(self.next_call - time.time(), self._run) | |
self._timer.start() | |
self.is_running = True | |
def stop(self): | |
self._timer.cancel() | |
self.is_running = False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment