Advertisement
yang_w

Twisted countdown loopingcall solution2

Feb 16th, 2014
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. from twisted.internet.task import LoopingCall
  2.  
  3. class Manager:
  4.    
  5.     def __init__(self):
  6.         self._job2loop = {}
  7.         self._jobDone = {}
  8.  
  9.     def register(self, task):
  10.         self._job2loop[task.name] = LoopingCall(task.job())
  11.         self._jobDone[task.name] = task.job_done
  12.  
  13.     def start(self, schedule):
  14.         if not type(schedule) is list:
  15.             schedule = [schedule]
  16.         for task, timer in schedule:
  17.             if task.name in self._job2loop:
  18.                 self._job2loop[task.name].start(timer, False)
  19.             else:
  20.                 print 'Job has not scheduled: %s' % task.name
  21.  
  22.     def check_end(self, task):
  23.         if self._jobDone[task.name]():
  24.             self._job2loop[task.name].stop()
  25.             del self._job2loop[task.name]
  26.             if not self._job2loop:
  27.                 reactor.stop()
  28.  
  29. class Countdown(object):
  30.  
  31.     def __init__(self, name, start):
  32.         self.name = name
  33.         self.counter = start
  34.        
  35.     def register(self, manager):
  36.         self.manager = manager
  37.         manager.register(self)
  38.        
  39.     def job_done(self):
  40.         if not self.counter:
  41.             return True
  42.         return False
  43.  
  44.     def job(self):
  45.         return self.count
  46.  
  47.     def count(self, finallize=lambda x: None):
  48.         print 'counter %s:' % str(self.name), self.counter, '...'
  49.         self.manager.check_end(self)
  50.         self.counter -= 1
  51.  
  52. mng = Manager()
  53. cntA = Countdown('AAA', 5)
  54. cntB = Countdown('BB', 10)
  55. cntC = Countdown('C', 7)
  56.  
  57. cntA.register(mng)
  58. cntB.register(mng)
  59. cntC.register(mng)
  60.  
  61. mng.start([(cntA, 1), (cntB, 0.3)])
  62. mng.start((cntC, 0.5))
  63.  
  64. from twisted.internet import reactor
  65. reactor.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement