Python任务调度之sched.docx
《Python任务调度之sched.docx》由会员分享,可在线阅读,更多相关《Python任务调度之sched.docx(6页珍藏版)》请在冰豆网上搜索。
Python任务调度之sched
Python任务调度之sched
这次我们主要讲解下Python自带模块当中的sched,不但小巧,也很强大,在实际应用中,某些场合还是可以用到的。
作为一名Linux的SA,我们已经习惯了用crontab,而sched提供了一种延迟处理机制,也可以理解为任务调度的另一种方式的实现。
scheduler.enter(delay,priority,action,argument)
●delay:
延迟时间
●
priority:
优先级
●
action:
回调函数
●
argument:
回调函数的参数
我们来写一个非常简单的例子:
importsched
importtime
scheduler=sched.scheduler(time.time,time.sleep)
deffunc(name):
print'action:
%s'%name,time.time()
print'START:
',time.time()
scheduler.enter(2,1,func,('fight',))
scheduler.enter(3,1,func,('makepeace',))
scheduler.run()
print'END:
',time.time()
运行结果如下:
START:
1339664955.4
action:
fight1339664957.4
action:
make
peace1339664958.4
END:
1339664958.4
我们再举一个简单的例子说明下sched的其它特性:
importsched
importtime
scheduler=sched.scheduler(time.time,time.sleep)
deffunc(name):
print'BEGIN:
%s:
'%name,time.time()
time.sleep
(2)
print'FINISH%s:
'%name,time.time()
print'START:
',time.time()
scheduler.enter(2,1,func,('fight',))
scheduler.enter(3,1,func,('makepeace',))
scheduler.run()
print'END:
',time.time()
运行结果如下:
START:
1339665268.12
BEGIN:
fight:
1339665270.12
FINISH
fight:
1339665272.12
BEGIN:
make
peace:
1339665272.12
FINISHmake
peace:
1339665274.12
END:
1339665274.12
我们仔细观察下两次任务调度的时间间隔,发现是同时运行的?
那又是为什么呢?
run()一直被阻塞,直到所有事件被全部执行完.
每个事件在同一线程中运行,所以如果一个事件的执行时间大于其他事件的延迟时间,那么,就会产生重叠。
重叠的解决方法是推迟后来事件的执行时间。
这样保证
没有丢失任何事件,但这些事件的调用时刻会比原先设定的迟。
上面的例子第二个事件在第一个事件运行结束后立即运行,因为第一个事件的执行时间足够长,已经超过第二个事件的预期开始时刻。
(本来应该1339660903秒运行)
我们再介绍另外一个保证action在同一时刻执行的函数:
scheduler.enterabs(time,priority,action,argument)
importsched
importtime
scheduler=sched.scheduler(time.time,time.sleep)
now=time.time()
deffunc(name):
print'action:
',time.time(),name
print'START:
',now
scheduler.enterabs(now+2,2,func,('makepeace',))
scheduler.enterabs(now+2,1,func,('fight',))
scheduler.run()
print'END:
',now
运行结果如下:
START:
1339666232.38
action:
1339666234.38fight
action:
1339666234.38makepeace
END:
1339666232.38
因为优先级的关系,所以先fight,然后再make
peace,打架是如此重要....总体来讲,如果想单纯的替换crontab的话,Scheduler框架更加适合,做延迟任务的调度处理的话sched还是可以考虑的。
如果我们想要取消任务调度,可以使用cancel()函数。
在上面的例子中出现了阻塞延迟的现象,如果引用线程机制就会避免这种情况的发生,我们简单举个例子:
importsched
importthreading
importtime
scheduler=sched.scheduler(time.time,time.sleep)
counter=0
defincrement_counter(name):
globalcounter
print'action:
%s'%name,time.time()
counter+=1
print'counter:
',counter
print'START:
',time.time()
action1=scheduler.enter(2,1,increment_counter,('action1',))
action2=scheduler.enter(3,1,increment_counter,('action2',))
t=threading.Thread(target=scheduler.run)
t.start()
scheduler.cancel(action1)
t.join()
print'counter:
',counter
print'END:
',time.time()
运行结果如下:
START:
1339666987.27
action:
action2
1339666990.27
counter:
1
counter:
1
END:
1339666990.27
因为run()函数会引起阻塞,所以我们需要采用线程机制的方法在另一个线程中通过对象的引用取消任务调度,这里只调度了action2方法。
本文出自“放飞翅膀,追求梦想”
博客,请务必保留此出处