Advertisement
yang_w

Untitled

Feb 17th, 2014
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.10 KB | None | 0 0
  1. import traceback
  2. from twisted.internet.task import LoopingCall
  3.  
  4. class Manager:
  5.    
  6.     def __init__(self):
  7.         self._job2loop = {}
  8.  
  9.     def register(self, *tasks):
  10.         for task in tasks:
  11.             self._job2loop[task.name] = LoopingCall(self.run_job, task)
  12.  
  13.     def start(self, *schedule):
  14.         for task, timer in schedule:
  15.             if task.name in self._job2loop:
  16.                 self._job2loop[task.name].start(timer, False)
  17.                 print 'Job %s started' % task.name
  18.             else:
  19.                 print 'Job not scheduled: %s' % task.name
  20.  
  21.     def run_job(self, task):
  22.         job = task.job()
  23.         try:
  24.             job()
  25.         except Exception, e:
  26.             self.exception_handler(task, e)
  27.         else:
  28.             if task.job_done():
  29.                 self.finalize(task)
  30.            
  31.     def exception_handler(self, task, e):
  32.         print 'Exception happened in %s.%s' % (task.name, task.job().__name__)
  33.         print e
  34.         print traceback.format_exc()
  35.         self.finalize(task)
  36.            
  37.     def finalize(self, task):
  38.         self._job2loop[task.name].stop()
  39.         del self._job2loop[task.name]
  40.         print '%s finalized' % task.name
  41.         if not self._job2loop:
  42.             reactor.stop()
  43.            
  44. class Countdown(object):
  45.  
  46.     def __init__(self, name, start):
  47.         self.name = name
  48.         self.counter = start
  49.        
  50.     def job_done(self):
  51.         if not self.counter:
  52.             return True
  53.         return False
  54.  
  55.     def job(self):
  56.         return self.count
  57.  
  58.     def count(self):
  59.         if self.counter <= 0:
  60.             raise ValueError, '%s.counter = %d, value must be greater than 0' % (self.name, self.counter)
  61.         print 'counter %s:' % str(self.name), self.counter, '...'
  62.         self.counter -= 1
  63.  
  64. cntA = Countdown('AAA', 5)
  65. cntB = Countdown('BB', 10)
  66. cntC = Countdown('C', 7)
  67. cntErr = Countdown('Err', 0)
  68.  
  69. mng = Manager()
  70.  
  71. mng.register(cntA, cntB, cntC, cntErr)
  72.  
  73. mng.start((cntA, 1), (cntB, 0.3))
  74. mng.start((cntC, 0.5), (cntErr, 1))
  75.  
  76. from twisted.internet import reactor
  77. reactor.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement