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()

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

while True:
# loop forever
print “%s %s %s” % (a.counter, b.counter, c.counter)

Leave a Reply

Your email address will not be published.