Skip to content

Instantly share code, notes, and snippets.

@alexbw
Created September 1, 2011 20:11
Show Gist options
  • Save alexbw/1187132 to your computer and use it in GitHub Desktop.
Save alexbw/1187132 to your computer and use it in GitHub Desktop.
A repeating timer in Python
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()
@xuancu
Copy link

xuancu commented Jul 13, 2022

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