如何结合 callLater 和 addCallback? [英] How to combine callLater and addCallback?

查看:24
本文介绍了如何结合 callLater 和 addCallback?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这太破了,希望你对我仁慈:

This is so broken, I hope you are merciful with me:

reactor.callLater(0, myFunction, parameter1).addCallback(reactor.stop)
reactor.run()

myFunction 返回延迟.

我希望我想做什么很清楚:

I hope it is clear what I want to do:

  • 反应器一运行,我就想调用myFunction.这就是我使用 0 作为延迟参数的原因.除了 callLater 就没有别的办法了吗?将延迟传递给它 0 看起来很有趣.
  • 我想在 myFunction 完成任务后立即停止反应器.
  • as soon as the reactor is running, I want to call myFunction. That is why I am using 0 as the delay parameter. Is there no other way except callLater? It looks funny to pass it a delay of 0.
  • I want to stop the reactor as soon as myFunction has completed the task.

我目前遇到的问题:

  • AttributeError: DelayedCall 实例没有属性addCallback".很公平!那么如何将回调放入由 myFunction 开始的回调链中?
  • exceptions.TypeError: stop() 只需要 1 个参数(给定 2 个).
  • AttributeError: DelayedCall instance has no attribute 'addCallback'. Fair enough! How do I put a callback in the callback chain started by myFunction then?
  • exceptions.TypeError: stop() takes exactly 1 argument (2 given).

为了解决第二个问题,我必须定义一个特殊的函数:

To solve the second problem I had to define a special function:

def stopReactor(result):
    gd.log.info( 'Result: %s' % result)
    gd.log.info( 'Stopping reactor immediatelly' )
    reactor.stop()

并将代码更改为:

reactor.callLater(0, myFunction, parameter1).addCallback(stopReactor)
reactor.run()

(由于 callLater 问题仍然无法工作,但 stopReactor 现在可以工作了)

(still not working because of the callLater problem, but stopReactor will work now)

除了定义一个额外的函数之外,真的没有其他方法可以调用 reactor.stop 吗?

Is there really no other way to call reactor.stop except by defining an extra function?

推荐答案

IreactorTime.callLaterDeferredtwisted.internet.task.deferLater 混合在一起.

from twisted.internet import reactor, task

d = task.deferLater(reactor, 0, myFunction, parameter1)
d.addCallback(lambda ignored: reactor.stop())
reactor.run()

这篇关于如何结合 callLater 和 addCallback?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆