#!/usr/bin/env python """ """ __author__ = 'Patrick Roberts' __copyright__ = 'Copyright 2004 Patrick Roberts' __license__ = 'Python' __version__ = '1.0' import wx class wxMyTimer(wx.Timer): """ There's a wxPyTimer() that let's you pass a func to be called when the timer ticks. It returns a timer object whose Start method must be called. """ def __init__(self, seconds, handler, repeat, **kwargs): """ handler is a function that be called with this object as its one arg. """ wx.Timer.__init__(self, None) # None means no events are sent, only self.Notify is called self.handler = handler vars(self).update(kwargs) self.Start(int(seconds * 1000), not repeat) def zzzStart(self, seconds, oneShot): #self.__class__.__bases__[0]. #if seconds <= 0: # assert oneShot == True # wx.CallAfter(self.handler) # oh, but now self.GetInterval() will fail when Restart is called by the handler #else: wx.Timer.Start(self, milliseconds=int(seconds * 1000), oneShot=oneShot) def Restart(self): #assert self.IsRunning() wx.Timer.Start(self, self.GetInterval(), self.IsOneShot()) # -1 for the interval oddly caused an exception in wxPython def Notify(self): #print 'tick' self.handler(self) def __del__(self): """This might not work right.""" self.Stop() # looks like del'ing a wxTimer doesn't stop it #print 'timer %r deleted' % self.handler wx.Timer.__del__(self) _to_do = {} # "_single_leading_underscore: weak "internal use" indicator (e.g. "from M import *" does not import objects whose name starts with an underscore)." def wxDoLater(seconds, f, name=None): """The advantage of this over wx.FutureCall is that it if you already called this to call some specific thing in the future, it will stop that timer.""" if name is None: name = f.func_code # func_code is the same for different closures of the same function; this seems to be a dicey way to spare me from providing a name old_timer = _to_do.pop(name, None) if old_timer: old_timer.Stop() # could maybe reuse the timer object?! _to_do[name] = wxMyTimer(seconds, lambda timer: f(), repeat=False) if __name__ == '__main__': pass