def resetTimer(self, initial = False): if self.timerObj: self.timerObj.cancel() #Does not care if timer is alive #if initial will try to set it to the firstTime today if initial: self.nextTrigger = self.firstTime else: self.nextTrigger = self.nextTrigger + self.timedelta if self.nextTrigger < datetime.now(): #If the trigger is in the past raise ValueError("Next PeriodicUpdater is in the past! \nDelta: "+repr(self.timedelta)+" nextTrigger: " + repr(self.nextTrigger)) log.event("Setting new trigger for", str(self.nextTrigger)) #Express the difference in time between the next trigger and now as an integer for the timer to wait difference = int((self.nextTrigger - datetime.now()).total_seconds())+1 #+1 because it rounds down to 23 hours 59 mins, 59 seconds log.event.debug("Trigger will fire in",str(timedelta(seconds = difference))) #First stop tracking this one deregisterThread(self.timerObj) del self.timerObj #And track the next one once it is made self.timerObj = threading.Timer(difference, self.startFunction) registerThread(self.timerObj) self.timerObj.daemon = True #We don't want this thread blocking system exit self.timerObj.start() #Starts the timer
def startFunction(self): log.event("PeriodicUpdater acquiring thread to run function") lock = getLockObject() lock.acquire() #Wait for whatever other function is executing now to finish try: self.function(*self.arg, **self.kwarg) finally: #Whether or not it errors we need to release the lock and reset the function lock.release() self.resetTimer() #Sets the next iteration
def saveAll(self, final = False): try: if len(self._objects): # if != 0 log.event("Saving all messages for",len(self._objects),"group"+("s" if len(self._objects) > 1 else "")) while len(self._objects): #While there are still objects in the list object = self._objects.pop() #Take it off and use it object._save() #_save must be a function that DOES NOT CALL addObject finally: #Whether or not we are successful, add another timer if not final: self.resetTimer()
def stopAllTimers(): log.event("Stopping all timers") for thread in _threadList: thread.cancel()