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() |
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 __init__(self, function, interval, *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()
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!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One question... What for self.finished.set() needed if program come there only if event already set.
And one more thing guys. I am trying to create timer wich can be paused and started again:
`class RXTimer( Thread ):
def init(self, interval, function, args=None, kwargs=None):
Thread.init(self)
self.interval = interval
self.function = function
self.args = args if args is not None else []
self.kwargs = kwargs if kwargs is not None else {}
self.paused = Event()
self.active = Event()
self.active.clear()
self.paused.set()
'`
But problem is self.paused.wait( self.interval ) do not lock thread and thread call self.function( *self.args, **self.kwargs ) without pauses.
Why?