Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # A solution to exercise 1 of the Twisted tutorial at http://krondo.com/?p=1333
- import time
- class Countdown(object):
- def __init__(self, name, ticks, rate):
- self.name, self.counter, self.rate = (name, ticks, rate)
- def count(self):
- print '{}: {:>2} ticks left at {} sec/tick ...'.format(self.name, self.counter, self.rate)
- self.counter -= 1
- class CountdownPool(object):
- def __init__(self, *args):
- self.pool = [Countdown(name, ticks, rate) for name, ticks, rate in args]
- self.pending = len(self.pool)
- def start(self):
- self.startTime = time.time()
- for ctdn in self.pool:
- self.count(ctdn)
- def count(self, ctdn):
- if ctdn.counter > 0:
- ctdn.count()
- reactor.callLater(ctdn.rate, self.count, ctdn)
- else:
- print 'Counter {} complete! ({:.3f} sec)'.format(ctdn.name, time.time()-self.startTime)
- self.pending -= 1
- if not self.pending: reactor.stop()
- from twisted.internet import reactor
- pool = CountdownPool(['one', 5, 1.0], ['two', 13, .3], ['tri', 8, .8])
- reactor.callWhenRunning(pool.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 ...
- tri: 5 ticks left at 0.8 sec/tick ...
- two: 5 ticks left at 0.3 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.901 sec)
- tri: 3 ticks left at 0.8 sec/tick ...
- one: 1 ticks left at 1.0 sec/tick ...
- tri: 2 ticks left at 0.8 sec/tick ...
- Counter one complete! (5.001 sec)
- tri: 1 ticks left at 0.8 sec/tick ...
- Counter tri complete! (6.402 sec)
- Stop!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement