]> defiant.homedns.org Git - pyshared.git/blob - scheduler.py
Initial commit
[pyshared.git] / scheduler.py
1 #!/usr/bin/env python
2 # -*- coding: iso-8859-15 -*-
3
4 import logging
5 import threading
6 from time import sleep
7
8
9 logger = logging.getLogger(__name__)
10
11 class Scheduler:
12         def __init__(self):
13                 self.lThreads = []
14                 self.pause = False
15                 self.autoclean()
16                 self.__lock_delay = threading.Lock()
17
18         def autoclean(self):
19                 logger.debug("Current number of threads: %d" % threading.active_count())
20                 self.add_thread(10, self.autoclean)
21                 for t in self.lThreads:
22                         if not t.isAlive():
23                                 self.lThreads.remove(t)
24
25         def stop(self):
26                 for t in self.lThreads:
27                         t.cancel()
28
29         def add_thread(self, time, function, args=[], kwargs={}):
30                 while(self.pause):
31                         sleep(1)
32                 k = [function, None, args, kwargs]
33                 t = threading.Timer(time, self.dispatch, k)
34                 t.setDaemon(True)
35                 t.setName(str(function))
36                 k[1] = t
37                 t.delayed = True
38                 t.start()
39                 self.lThreads.append(t)
40
41         def dispatch(self, function, timer, args, kwargs):
42                 while True:
43                         with self.__lock_delay:
44                                 still_running = False
45                                 for t in self.lThreads:
46                                         if t.name == str(function) and t.isAlive() and t.ident != timer.ident and not t.delayed:
47                                                 still_running = True
48                                                 break
49                                 if not still_running:
50                                         t.delayed = False
51                                         break
52                         logger.debug("Delaying execution of Thread %s", t.name)
53                         # Another Thread still running, delay execution
54                         sleep(0.1)
55                 try:
56                         function(*args, **kwargs)
57                 except:
58                         logger.exception("Dispatcher exception of %s:", t.name)
59                         logger.error("Current number of threads: %d" % threading.active_count())
60
61
62 pScheduler = Scheduler()
63
64 if __name__ == "__main__":
65         logging.basicConfig(level=logging.DEBUG)
66         def test():
67                 pScheduler.add_thread(0.1, test)
68                 print "test"
69                 sleep(1)
70                 print "end"
71         test()
72
73         while(1):
74                 sleep(0.1)