2.twisted入门

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()

转载于:https://www.cnblogs.com/wolover/p/5749514.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值