3 from datetime import datetime, timedelta
7 ### more generic code for waiting for any number of things
8 ### within a given timeframe i.e. given some timeout/silent/period
9 ### takes in argument a list of tasks that are instances
10 ### of a CompleterTask subclass
12 def __init__ (self, tasks, verbose=True):
15 def run (self, timeout_timedelta, silent_timedelta, period=None):
16 timeout = datetime.now()+timeout_timedelta
17 timeout_minutes = timeout_timedelta.total_seconds()/60
18 graceout = datetime.now()+silent_timedelta
19 silent_minutes = silent_timedelta.total_seconds()/60
20 period_seconds=int(period.total_seconds())
22 utils.header("max timeout is %d minutes, silent for %d minutes (period is %s s)"%\
23 (timeout_minutes,silent_minutes,period_seconds))
28 success=task.run (silent=datetime.now() <= graceout)
29 if success: fine.append(task)
30 for task in fine: tasks.remove(task)
31 if not tasks: return True
32 if datetime.now() > timeout:
34 print task.failure_message()
37 print '%ds..'%period_seconds,
38 time.sleep(period_seconds)
43 #################### CompleterTask
44 ### . run(silent) (return True or False)
45 ### silent is an input boolean indicating if we're within the silent period
46 ### . failure() (print a message)
48 ########## expectations (+ first arg self)
49 # failure() (to describe which went wrong once it's over)
57 def run (self, silent):
58 result=self.actual_run()
60 print '+' if result else '.',
63 print self.message(),"->","OK" if result else "KO"
65 def message (self): return "you-need-to-redefine-message"
66 def failure_message (self): return "you-need-to-redefine-failure_message"
69 class TaskTest (CompleterTask):
71 def __init__ (self,max):
73 self.counter=TaskTest.counter
75 self.delay=random.random()*max
76 self.fire=datetime.now()+timedelta(seconds=self.delay)
78 return datetime.now()>=self.fire
80 return "Task %d - delay was %d s"%(self.counter,self.delay)
82 def failure_message (self): return "BOTTOM LINE: FAILURE with task (%s)"%self.counter
87 print "Usage: <command> number_tasks max_random timeout_s silent_s period_s"
89 [number,max,timeout,silent,period]= [ int(x) for x in sys.argv[1:]]
90 tasks = [ TaskTest(max) for i in range(number)]
91 success=Completer(tasks,verbose=True).run(timedelta(seconds=timeout),
92 timedelta(seconds=silent),
93 timedelta(seconds=period))
94 print "OVERALL",success
96 if __name__ == '__main__':