- sched
这是一个事件调度程序的类
1 import sched
2 import time
3
4 scheduler = sched.scheduler(time.time, time.sleep)
5
6 def print_event(name):
7 print('EVNET:', time.time(), name)
8 # time.sleep(2)
9 # print('EVNET:', time.time(), name)
10
11 now = time.time()
12 print('start:', time.time())
# 第一个参数是设定延迟时间,第二个是优先级,
# 第三个是回调函数,第四个是回调函数参数构成的元组
13 scheduler.enter(2,2print_event, ('first',))
14 scheduler.enter(3,2print_event, ('second',))
15 scheduler.run()
若出现重叠事件,例如在回调函数中等待,那么在它之后的事件必须在第一个事件完成之后才能运行。另外方法需改为 scheduler.enterabs()。
如果需要取消一个任务,则需要在线程中取消它:
import sched
import threading
import time
scheduler = sched.scheduler(time.time, time.sleep)
# Set up a global to be modified by the threads
counter = 0
def increment_counter(name):
global counter
print 'EVENT:', time.time(), name
counter += 1
print 'NOW:', counter
print 'START:', time.time()
e1 = scheduler.enter(2, 1, increment_counter, ('E1',))
e2 = scheduler.enter(3, 1, increment_counter, ('E2',))
# Start a thread to run the events
t = threading.Thread(target=scheduler.run)
t.start()
# Back in the main thread, cancel the first scheduled event.
scheduler.cancel(e1)
# Wait for the scheduler to finish running in the thread
t.join()
print 'FINAL:', counter
- bisect
这个模块是用来进行查找的,还可以用来向序列中插入新元素。核心思想是二分查找。
示例 根据一个分数,找到它所对应的成绩
>>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
... i = bisect.bisect(breakpoints, score)
... return grades[i]...
>>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
['F', 'A', 'C', 'C', 'B', 'A', 'A']
排序非常耗时。得到一个有序序列之后,可以用 bisect.insort 来插入元素到一个有序序列。
import bisect
import random
SIZE=7
8
8
random.seed(1729)
my_list = []
for i in range(SIZE):
new_item = random.randrange(SIZE*2)
bisect.insort(my_list, new_item)
print('%2d ->' % new_item, my_list)
输出
网友评论