Created
September 1, 2011 20:11
-
-
Save alexbw/1187132 to your computer and use it in GitHub Desktop.
A repeating timer in Python
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
class RepeatingTimer(object): | |
""" | |
USAGE: | |
from time import sleep | |
def myFunction(inputArgument): | |
print(inputArgument) | |
r = RepeatingTimer(0.5, myFunction, "hello") | |
r.start(); sleep(2); r.interval = 0.05; sleep(2); r.stop() | |
""" | |
def __init__(self,interval, function, *args, **kwargs): | |
super(RepeatingTimer, self).__init__() | |
self.args = args | |
self.kwargs = kwargs | |
self.function = function | |
self.interval = interval | |
def start(self): | |
self.callback() | |
def stop(self): | |
self.interval = False | |
def callback(self): | |
if self.interval: | |
self.function(*self.args, **self.kwargs) | |
Timer(self.interval, self.callback, ).start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
from threading import Timer
import time
class RepeatingTimer(object):
"""
USAGE:
from time import sleep
r = RepeatingTimer(_print, 0.5, "hello")
r.start(); sleep(2); r.interval = 0.05; sleep(2); r.stop()
"""
def dowork():
global count
count = count + 1
count = 0
timer = RepeatingTimer(dowork, 0.0001)
timer.start()
time.sleep(1.0)
timer.stop()
print(count)
output:
3039
The theoretical output should be 10000. But here it is 3039. I'm not understanding why!