1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 import time, threading
26 from threading import Thread
27 import warn
28 warn = warn.Warn("PeriodicExecution")
29
30 try:
31 True
32 except:
33 __builtins__['True'] = 1
34 __builtins__['False'] = 0
35
37 """ Performs execution of |periodicfunction| in the time
38 |now| + timetobegin, and periodically repites every |timeinterval|. """
39 - def __init__(self, periodicfunction, timetobegin=0, timeinterval=604800):
40 self.periodicfunction = periodicfunction
41 self.timetobegin = timetobegin
42 self.timeinterval = timeinterval
43 Thread.__init__(self)
44 self.cond = threading.Condition()
45 self.exit = None
46 self.start()
47
49 self.cond.acquire()
50 self.exit = True
51 self.cond.notify()
52 self.cond.release()
53
55 while True:
56 self.cond.acquire()
57 if not self.exit: self.cond.wait(self.timetobegin)
58 self.cond.release()
59 if self.exit: break
60 start = time.time()
61 try:
62 self.periodicfunction()
63 except Exception, e:
64 warn.warn("PeriodicExecution",e)
65
66
67 self.timetobegin = self.timeinterval - (time.time() - start) % \
68 self.timeinterval
69
71 - def __init__(self, fexecution, exec_every = 1, exec_time = None):
72 self.__exec_every = exec_every
73 self.__changes = 0
74 self.__exec_time = exec_time
75 self.__fexecution = fexecution
76 if exec_time:
77 self.__perexe = PeriodicExecution(self.execute,exec_time,exec_time)
78 else:
79 self.__perexe = None
80
82 if self.__changes == 0: return
83 self.__fexecution()
84
86 self.__changes = 1 + self.__changes
87 if self.__changes > 0 and self.__exec_every % self.__changes == 0:
88 self.__fexecution()
89 self.__changes = 0
90
92 if self.__perexe: self.__perexe.stop()
93