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
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Last Update:
__revision__ = '0.1'
__author__ = 'lxd'
import threading
import time
class TimeThread(threading.Thread):
"""等待线程
"""
def __init__(self, name, seconds):
threading.Thread.__init__(self, name = name)
self.seconds = seconds
def run(self):
time.sleep(self.seconds)
class TimeWorks(object):
def __init__(self):
self.wait_works = {}#等待工作列表,包括工作的所有细节
self.wait_times_threads = []#线程列表
def setTime(self, name, data, seconds):
"""将data放入等待工作列表中,并将工作放入线程中等待
name如果已存在,则会覆盖原来的
"""
self.wait_works.update({name:data})
atime = TimeThread(name, seconds)
atime.setDaemon(True)
atime.start()
self.wait_times_threads.append(atime)
def checkTimeThread(self):
"""获得时间已到的工作
"""
for atime in self.wait_times_threads:
if not atime.isAlive():
self.wait_times_threads.remove(atime)
return self.wait_works.pop(atime.name)
if __name__ == '__main__':
print 'start'
timeWorks = TimeWorks()
build = {'kind':'build', 'name':'build1', 'pos':(1, 2)}
timeWorks.setTime('build1', build, 5)
farm = {'kind':'farm', 'name':'tom', 'pos':(3, 5)}
timeWorks.setTime('farm1', farm, 3)
def build_something(data):
print 'build_something', str(data)
def farm_something(data):
print 'farm_something', str(data)
i = 0
while True:
print 'do_something', i
i += 1
time.sleep(1)
data = timeWorks.checkTimeThread()
if data:
if data['kind'] == 'build':
build_something(data)
elif data['kind'] == 'farm':
farm_something(data)
|