新来的扭曲,只是尝试一些延迟的东西。我有以下代码组成了 100 个延迟调用的列表 - 每个都等待随机时间并返回一个值。该列表打印结果并最终终止反应器。
但是,我很确定我停止反应堆的方式可能......不是很好。
__author__ = 'Charlie'
from twisted.internet import defer, reactor
import random
def getDummyData(x):
"""returns a deferred object that will have a value in some random seconds
sets up a callLater on the reactor to trgger the callback of d"""
d = defer.Deferred()
pause = random.randint(1,10)
reactor.callLater(pause, d.callback, (x, pause))
return d
def printData(result):
"""prints whatever is passed to it"""
print result
def main():
"""makes a collection of deffered calls and then fires them. Stops reactor at end"""
deferred_calls = [getDummyData(r) for r in range(0,100)]
d = defer.gatherResults(deferred_calls, consumeErrors = True)
d.addCallback(printData)
# this additional callback on d stops the reacor
# it fires after all the delayed callbacks have printed their values
# the lambda ignored: ractor.stop() is required as callback takes a function
# that takes a parameter.
d.addCallback(lambda ignored: reactor.stop())
# start the reactor.
reactor.run()
if __name__ == "__main__":
main()
我假设通过添加回调:
d.addCallback(lambda ignored: reactor.stop())
收集到的结果实际上在所有延迟项目上添加了回调?
如果是这样,那么可能有更优雅/正确的方法来做到这一点?
干杯!