码迷,mamicode.com
首页 > 其他好文 > 详细

2.twisted入门

时间:2016-08-08 15:44:57      阅读:354      评论:0      收藏:0      [点我收藏+]

标签:

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

2.twisted入门

标签:

原文地址:http://www.cnblogs.com/wolover/p/5749514.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!