I have recently started learning Python and part of the simple app I am making includes a timer with a hh:mm:ss display running in its own thread.
Looking around the web
Here's how to make a one-shot into a periodic event, e.g. with sched
: if the function must make its own scheduler and be the only thing running on its thread:
def tick(self, display, alarm_time, scheduler=None):
# make a new scheduler only once & schedule this function immediately
if scheduler is None:
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(0, 1, self.tick, ([display, alarm_time, scheduler]))
scheduler.run()
# reschedule this function to run again in a minute
scheduler.enter(1, 1, self.tick, (display, alarm_time, scheduler]))
# do whatever actual work this function requires, e.g.:
self.updateTime(display)
If other events must also be scheduled in the same thread then the scheduler must be made and owned "elsewhere" -- the if
part above can get refactored into another method, e.g.:
def scheduleperiodic(self, method, *args):
self.scheduler = sched.scheduler(time.time, time.sleep)
self.scheduler.enter(0, 1, method, args)
# whatever else needs to be scheduled at start, if any, can go here
self.scheduler.run()
def tick(self, display, alarm_time):
# reschedule this function to run again in a minute
self.scheduler.enter(60, 1, self.tick, (display, alarm_time))
# do whatever actual work this function requires, e.g.:
self.updateTime(display)
Again, of course and as always with sched
, while the scheduler is running, it (and the scheduled event callbacks) will "take over" the thread in question (so you'll need to hive off a separate thread for it if you need other things to be happening at the same time).
If you need to use this kind of idiom in many functions it could be refactored into a decorator, but that would somewhat mask the underlying simplicity of the idiom, so I prefer this simple, overt use. BTW, note that time.time and time.sleep use seconds, not minutes, as their unit of time, so you need 60, not one, to indicate "a minute from now";-).