Simple example of using the threading Timer class in python

[cc lang=”python”]
#!/usr/bin/env python
# simple example of threading.Timer in python

import time, threading

class Counter(object):
def __init__(self, initial = 0, update_interval = 5):
self.counter = initial
self.update_interval = update_interval

def inc(self):
self.counter += 1
# Timer only runs once so call recursively in inc()
threading.Timer(self.update_interval, self.inc).start()

a = Counter()
b = Counter(50, 10)
c = Counter(1000, 1)

for ct in (a, b, c):
# increment counter and start timer thread in each object
ct.inc()

while True:
# loop forever
time.sleep(1)
print “%s %s %s” % (a.counter, b.counter, c.counter)
[/cc]

Leave a Reply

Your email address will not be published. Required fields are marked *