twisted——scheduling tasks

如果我们想在reactor开始后,能执行一些方法,可以使用reactor.callLater()方法和twisted.internet.task中的方法。

1、使用reactor.callLater()

calllater.py

1 from twisted.internet import reactor
2 
3 def fun(s):
4     print "3 seconds later %s" % s
5     reactor.stop()
6 
7 reactor.callLater(3, fun, "ha!")
8 reactor.run()

 

2、如果我们需要使用到方法返回的数据,那么就需要借用task.deferLater()方法,它将会生成Defered,并且建立延迟调用。

deferlater.py

 1 from twisted.internet import task, reactor
 2 
 3 def f(s):
 4     reactor.stop()
 5     return "3 seconds later %s " % s
 6     
 7 
 8 d=task.deferLater(reactor, 3, f, 'ha!')
 9 
10 def called(result):
11     print result
12     # reactor.stop()
13 
14 d.addCallback(called)
15 
16 reactor.run()

 

3、如果我们想重复的调用某一个方法,可以使用task.LoopingCall()方法。

1 def runEverySecond():
2     print "a second has passed"
3 
4 l=task.LoopingCall(runEverySecond)
5 l.start(1.0)
6 
7 reactor.run()

 

如果我们需要取消任务。

1 def f():
2     print "I would't run .. "
3 
4 callID=reactor.callLater(5, f)
5 callID.cancel()
6 reactor.run()

 

需要注意的是,我们要想那些任务能够执行,则必须通过reactor.run()来开始。

posted @ 2014-08-18 00:20  红尘眷恋  阅读(385)  评论(0编辑  收藏  举报