PageRenderTime 71ms CodeModel.GetById 58ms app.highlight 6ms RepoModel.GetById 4ms app.codeStats 1ms

/library/Timer.py

http://pyjamas.googlecode.com/
Python | 88 lines | 83 code | 4 blank | 1 comment | 1 complexity | f50b7c72c592026b02a545b9be2f436a MD5 | raw file
 1#Timer().hookWindowClosing()
 2timers = []
 3
 4class Timer:
 5    MIN_PERIOD = 1
 6    
 7    def __init__(self, delay = 0, object = None):
 8        self.isRepeating = False
 9        self.timerId = 0
10
11        self.listener = object
12        if delay >= Timer.MIN_PERIOD:
13            self.schedule(delay)
14    
15    def clearInterval(self, id):
16        JS("""
17        $wnd.clearInterval(id);
18        """)
19
20    def clearTimeout(self, id):
21        JS("""
22        $wnd.clearTimeout(id);
23        """)
24
25    def createInterval(self, timer, period):
26        JS("""
27        return $wnd.setInterval(function() { timer.fire(); }, period);
28        """)
29
30    def createTimeout(self, timer, delay):
31        JS("""
32        return $wnd.setTimeout(function() { timer.fire(); }, delay);
33        """)
34
35    # TODO - requires Window.addWindowCloseListener
36    def hookWindowClosing(self):
37        pass
38    
39    def cancel(self):
40        global timers
41        
42        if self.isRepeating:
43            self.clearInterval(self.timerId)
44        else:
45            self.clearTimeout(self.timerId)
46        timers.remove(self)
47
48    def run(self):
49        if self.listener:
50            self.listener.onTimer(self.timerId)
51    
52    def schedule(self, delayMillis):
53        global timers
54        
55        if delayMillis < Timer.MIN_PERIOD:
56            alert("Timer delay must be positive")
57        self.cancel()
58        self.isRepeating = False
59        self.timerId = self.createTimeout(self, delayMillis)
60        timers.append(self)
61
62    def scheduleRepeating(self, periodMillis):
63        global timers
64
65        if periodMillis < Timer.MIN_PERIOD:
66            alert("Timer period must be positive")
67        self.cancel()
68        self.isRepeating = True
69        self.timerId = self.createInterval(self, periodMillis)
70        timers.append(self)
71
72    # TODO: UncaughtExceptionHandler, fireAndCatch
73    def fire(self):
74        self.fireImpl()
75
76    def fireImpl(self):
77        global timers
78        
79        if not self.isRepeating:
80            timers.remove(self)
81
82        self.run()
83
84    def getID(self):
85        return self.timerId
86
87
88