Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # A solution to exercise 2 of the Twisted tutorial at http://krondo.com/?p=1333
- import time
- from twisted.internet.task import LoopingCall
- class CountdownMonitor(object):
- def __init__(self):
- self.countdowns = []
- def register(self, *args):
- self.countdowns.extend(args)
- def start(self):
- self.startTime = time.time()
- def timeElapsed(self):
- return time.time() - self.startTime
- def finalize(self, ctdn):
- self.countdowns.remove(ctdn)
- if not self.countdowns:
- reactor.callLater(0, reactor.stop)
- class Countdown(object):
- def __init__(self, name, ticks, rate, monitor):
- self.name, self.counter, self.rate, self.monitor = \
- name, ticks, rate, monitor
- self.looper = LoopingCall(self.count)
- monitor.register(self)
- def start(self):
- self.looper.start(self.rate)
- def count(self):
- if self.counter == 0:
- self.looper.stop()
- print 'Counter {} complete! ({:.3f} sec)'.format(self.name, monitor.timeElapsed())
- self.monitor.finalize(self)
- else:
- print '{}: {:>2} ticks left at {} sec/tick ...'.format(self.name, self.counter, self.rate)
- self.counter -= 1
- from twisted.internet import reactor
- monitor = CountdownMonitor()
- reactor.callWhenRunning(monitor.start)
- data = [['one', 5, 1.0], ['two', 13, .3], ['tri', 8, .8]]
- for name, ticks, rate in data:
- reactor.callWhenRunning(Countdown(name, ticks, rate, monitor).start)
- print 'Start!'
- reactor.run()
- print 'Stop!'
- #### Output ####
- Start!
- one: 5 ticks left at 1.0 sec/tick ...
- two: 13 ticks left at 0.3 sec/tick ...
- tri: 8 ticks left at 0.8 sec/tick ...
- two: 12 ticks left at 0.3 sec/tick ...
- two: 11 ticks left at 0.3 sec/tick ...
- tri: 7 ticks left at 0.8 sec/tick ...
- two: 10 ticks left at 0.3 sec/tick ...
- one: 4 ticks left at 1.0 sec/tick ...
- two: 9 ticks left at 0.3 sec/tick ...
- two: 8 ticks left at 0.3 sec/tick ...
- tri: 6 ticks left at 0.8 sec/tick ...
- two: 7 ticks left at 0.3 sec/tick ...
- one: 3 ticks left at 1.0 sec/tick ...
- two: 6 ticks left at 0.3 sec/tick ...
- two: 5 ticks left at 0.3 sec/tick ...
- tri: 5 ticks left at 0.8 sec/tick ...
- two: 4 ticks left at 0.3 sec/tick ...
- one: 2 ticks left at 1.0 sec/tick ...
- two: 3 ticks left at 0.3 sec/tick ...
- tri: 4 ticks left at 0.8 sec/tick ...
- two: 2 ticks left at 0.3 sec/tick ...
- two: 1 ticks left at 0.3 sec/tick ...
- Counter two complete! (3.900 sec)
- one: 1 ticks left at 1.0 sec/tick ...
- tri: 3 ticks left at 0.8 sec/tick ...
- tri: 2 ticks left at 0.8 sec/tick ...
- Counter one complete! (5.000 sec)
- tri: 1 ticks left at 0.8 sec/tick ...
- Counter tri complete! (6.400 sec)
- Stop!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement