Go to the documentation of this file.00001 '''
00002 ProcTimer.py: precise scheduling of process callbacks (Procs) with variable delays
00003
00004 - triggers callbacks with variable delays
00005 - needs to be called at an update rate that is higher than the shortest Proc delay
00006 - keeps an error term per proc that ensures that over time all the varying proc rates will be exactly
00007 as specified even though ProcTimer is driven at one fixed rate
00008 - if a high precision is required even for short runs than the update rate should be significantly
00009 faster than the fastest delay proc installed
00010
00011 (c) Gsk 18/07/2010
00012 '''
00013
00014 import time
00015
00016 class Proc:
00017
00018 def __init__(self, ms_delay, id):
00019 self.delay = ms_delay
00020 self.id = id
00021
00022 self.elapsed = ms_delay
00023 self.carry = 0
00024
00025
00026 def doTick(self, ms_elapsed):
00027 bProc = False
00028 self.elapsed = self.elapsed + ms_elapsed
00029
00030
00031
00032 elapsed = self.elapsed + self.carry
00033 if(elapsed >= self.delay):
00034 bProc = True
00035 self.carry = self.carry + (self.elapsed - self.delay)
00036 self.elapsed = 0
00037
00038 return bProc
00039
00040
00041 class ProcTimer:
00042
00043 def __init__(self):
00044 self.procs = {}
00045 self.lastTick = None
00046
00047 def addProc(self, id, delay, callback):
00048 ''' add a Proc to this ProcTimer
00049 - the callback will be called with the timer id as first parameter
00050 - delay is the delay (in miliseconds) between procs '''
00051 proc = Proc(delay, id)
00052 self.procs[id] = (proc, callback)
00053
00054 def delProc(self, id):
00055 del self.procs[id]
00056
00057 def update(self):
00058 if len(self.procs) == 0:
00059 self.lastTick = None
00060 return
00061
00062
00063 thisTick = time.time()
00064 if self.lastTick == None:
00065 self.lastTick = thisTick - 1
00066
00067 delta_ms = int((thisTick - self.lastTick)*1000.0)
00068 self.lastTick = thisTick
00069
00070 for id, entry in self.procs.items():
00071 proc = entry[0]
00072 if proc.doTick(delta_ms):
00073 callback = entry[1]
00074 callback(proc.id)
00075