forked from boskee/Minecraft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.py
81 lines (61 loc) · 1.97 KB
/
timer.py
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# Imports, sorted alphabetically.
# Python packages
# Nothing for now...
# Third-party packages
# Nothing for now...
# Modules from this project
# Nothing for now...
import threading
import time
__all__ = (
'TimerTask', 'Timer',
)
class TimerTask:
def __init__(self, ticks, callback, speed):
self.ticks = self.expire = ticks
self.callback = callback
self.speed = speed
def progress(self):
return self.ticks / self.expire
# Timer used in furnace and redstone circuits
class Timer(threading.Thread):
def __init__(self, interval, name=None):
super(Timer, self).__init__(name=name)
self.queue = [None]
self.interval = interval
self._stop = threading.Event()
def add_task(self, ticks, callback, speed=1):
if ticks == 0 and callback is not None:
callback()
task = TimerTask(ticks, callback, speed)
for index, _task in enumerate(self.queue):
if _task is None:
self.queue[index] = task
return index
self.queue.append(task)
return len(self.queue) - 1
def remove_task(self, index):
if index >= len(self.queue):
return False
self.queue[index] = None
return True
def run(self):
while True:
time.sleep(self.interval)
if self._stop.is_set(): return
for index, _task in enumerate(self.queue):
if _task is None:
continue
self.queue[index].ticks -= self.interval * self.queue[index].speed
if self.queue[index].ticks <= 0:
self.queue[index].callback()
self.queue[index] = None
def progress(self, index):
if index >= len(self.queue):
return 0
if self.queue[index] is not None:
return self.queue[index].progress()
else:
return 0
def stop(self):
self._stop.set()