twisted入门

1. callWhenRunning   callLater的使用
__author__ = 'zhoukunpeng'
from twisted.internet import reactor
import  time
def hello():
    print "hello from the reactor loop!"
def  printTime(aa):
    print time.localtime()
    print aa
reactor.callWhenRunning(hello)
reactor.callLater(3,printTime,123)
print "start the reactor"
reactor.run()
reactor.callWhenRunning(hello)  reactor.callLater(3,printTime,123)是reactor的两个注册器。 通过此两个注册器可以注册相关的回调函数。在条件满足时,自动回调。 由于twisted是单线程的,所以,回调函数中必须保证无拥塞!注意:注册回调函数时,可以指定参数的传递。且参数可以有默认值。

2.task.LoopingCall 的使用
还有一个常用的回调函数是:

from twisted.internet import task
task_test=task.LoopingCall(test)
task_test.start(60)   #立刻执行,以后每隔60s执行一次
加入递归调用后如下:
__author__ = 'zhoukunpeng'
from twisted.internet import reactor
import  time
def hello():
    print "hello from the reactor loop!"
def  printTime(aa):
    print time.localtime()
    print aa
    reactor.callLater(3,printTime,123)
reactor.callWhenRunning(hello)
reactor.callLater(3,printTime,123)
print "start the reactor"
reactor.run()

3.defer.callLater的使用

from twisted.internet import  reactor
from twisted.internet.task import deferLater
from twisted.internet.defer import inlineCallbacks
@inlineCallbacks
def sleep(seconds):
a=yield deferLater(reactor,seconds,lambda:None)
print "sleep %s"%seconds
sleep(3)
reactor.run()
posted on 2016-08-08 15:37  wolover  阅读(224)  评论(0编辑  收藏  举报