I created a prototype module to create complex timer schedules in python. Class prototypes emulate Timer objects, each with its own waiting time, repeat the objects that group Timer and other Repeat objects, and the Schedule class, only to contain entire constructions or instances of Timers and Repeat. The design can be complex as needed and must be flexible.
Each of these three classes has a method .run()that allows you to go through the entire schedule. Regardless of the class, the method .run()starts a timer, a repeated group for a certain number of iterations, or a schedule.
Is this polymorphism-oriented approach sound or dumb? What are other suitable approaches that I should consider in order to create such a universal utility that makes it easy to combine all the building blocks as difficult as possible?
Thank!
Here is the module code:
from time import time, sleep
class Timer:
"""
Timer object with duration.
"""
def __init__(self, duration):
self.duration = duration
def run(self):
print "Waiting for %i seconds" % self.duration
wait(self.duration)
chime()
class Repeat:
"""
Repeat grouped objects for a certain number of repetitions.
"""
def __init__(self, objects=[], rep=1):
self.rep = rep
self.objects = objects
def run(self):
print "Repeating group for %i times" % self.rep
for i in xrange(self.rep):
for group in self.objects:
group.run()
class Schedule:
"""
Groups of timers and repetitions. Maybe redundant with class Repeat.
"""
def __init__(self, schedule=[]):
self.schedule = schedule
def run(self):
for group in self.schedule:
group.run()
def wait(duration):
"""
Wait a certain number of seconds.
"""
time_end = time() + float(duration)
time_diff = time_end - time()
while time_diff > 0:
sleep(1)
time_diff = time_end - time()
def chime():
print "Ding!"
source
share